Function pointer link stubs

Share


Last week been test-driving some C code again and found that not much people are familiar with the "function pointer link stub". This is an excellent technique in C to dynamically replace library calls without adjusting the library.

Imagine, you are working on some embedded software. You will have a couple of libraries that you use, but you won't link to it when unit testing. Instead you stub them out. But, a link stub cannot be adjusted on run-time, so how do you handle this? With... "function pointer link stubs".

The idea is simple. You stub out the library and your stub calls a function pointer when its set. When not set, it just returns success.

Here is some example code:

.h (in a library where we cannot change the header)

int aLibraryCallWeCannotChange(int param);

----------------
aLibraryStub.h

extern int (*aLibraryCallWeCannotChangeFp)(int param);

-----------------
aLibraryStub.c

int aLibraryCallWeCannotChange(int param)
{
   if (aLibraryCallWeCannotChangeFp) aLibraryCallWeCannotChangeFp(param);
   return 0;
}

int (*aLibraryCallWeCannotChangeFp)(int param) = NULL;

-------------------------
TestThatUsesLibrary.cpp

TEST_GROUP(blah)
{
   void setup()
   {
       UT_PTR_SET(aLibraryCallWeCannotChangeFp, dynamicStubOfALibraryCall);
   }
}

Now it is easy to place the code of your stub close to your tests and you will never have to change the linker stub code.

Read more

ขยายกิจการองค์กร

ขยายกิจการองค์กร

อีกบทเรียนที่ผมได้จากหนังสือ Slack: Getting Past Burnout, Busywork, and the Myth of Total Efficiency ของ Tom DeMarco คือมุมมองใหม่สำหรับการเติบโตของบริษัท ตลอดมา ผมมักจะต่อต้านการแก้ปัญหางานไม่ทันด้วยการเพิ่มคน เพราะการเพิ่มคนเป็นกลยุทธ์ระดับองค์กร แต่งานไม่ทั

By Chokchai
คนไม่ใช่สิ่งทดแทนกันได้ (People are not Fungible)

คนไม่ใช่สิ่งทดแทนกันได้ (People are not Fungible)

ในปี 2546 นักศึกษาคณะวิทยาศาสตร์ที่เรียนอยู่ที่ศูนย์รังสิตมาตลอดแบบผม ได้มีโอกาสเข้าเมืองไปเรียนที่ธรรมศาสตร์ ท่าพระจันทร์ เป็นครั้งแรก นอกจากจะตื่นตาตื่นใจกับของอร่อยมากมายรอบมหาวิทยาลัยแล้ว บรรยากาศที่ศูนย์ท่าพระจันทร์มันมีมนต์ขลังแปลก ๆ ตัวผมได้

By Chokchai
ทำไม System Analyst ถึงไม่เชื่อ Design จากทีม

ทำไม System Analyst ถึงไม่เชื่อ Design จากทีม

บ่อยครั้งที่ผมได้ยินน้อง ๆ ออดส์ทีม (ODT) เล่าว่า งานที่ทำอยู่ไม่ท้าทายเลย เพราะเพียงได้รับ Specification มาจาก System Analyst (SA) หรือ Tech Lead ที่เป็นพนักงาน แล้วน้องก็มีหน้าที่เขียนโค้ดตามนั้นไปอย่างเดียว บ่

By Chokchai