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

Distributed Decision Making

Distributed Decision Making

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

By Chokchai
Risk Management: The Hard Test

Risk Management: The Hard Test

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

By Chokchai
วิธีปรับเวลาการนอน

วิธีปรับเวลาการนอน

ผมเดินทางกลับมาจาก Conference ของ Berkeley ที่ซานฟรานซิสโก เครื่องลงที่สนามบินสุวรรณภูมิประมาณ 22:30 น. กว่าจะถึงบ้านก็เกือบเที่ยงคืน ยังดีที่ขากลับไม่เหนื่อยเท่าขาไป เพราะลองซื้อหมอนรองคอจาก Duty Free ที่ซานฟรานซิสโกมาใช้ดู หมอนเป็นลายการ์ตูน มีรูปสะพาน

By Chokchai
เร็วแค่ไหนก็ไร้ค่า ถ้าไปผิดทาง

เร็วแค่ไหนก็ไร้ค่า ถ้าไปผิดทาง

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

By Chokchai