Function pointer link stubs


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

เสน่ห์ของ ScrumMaster

เสน่ห์ของ ScrumMaster

บางครั้งผมจะได้ยินคำถามเวลาไปงานแลกเปลี่ยนความรู้กับวง ScrumMaster ว่า ทำไงดี ทีมไม่เปิดใจให้ เข้าถึงทีมยาก ตอนผมนั่งในวงนั้น ผมก็ไม่รู้จะตอบยังไง เพราะผมไม่มีปัญหานี้ วันก่อน มีเพื่อนร่วมงานให้ feedback ผมว่า ผมมีพลังพิเศษ ทำให้คนไว้ใจ อยากเข้ามาปรึ

By Chokchai
ความหมายของที่ซ่อนอยู่ใน Just In Time

ความหมายของที่ซ่อนอยู่ใน Just In Time

วันหนึ่ง มีเด็กน้อยคนหนึ่ง กำลังจะขึ้นเครื่องบิน เด็กน้อยร้องไห้กระจองอแง อยู่ตรง security check เพราะว่าปลาทองที่เค้าจับมาได้ 2 ตัวนั้น ไม่สามารถเอาขึ้นเครื่องได้ เพราะมีน้ำอยู่ ยิ่งเด็กร้องนาน พ่อแม่ก็ยิ่งเครียด แล้วก็

By Chokchai
Boring tasks -> Purpose

Boring tasks -> Purpose

วันก่อน มีเพื่อน ScrumMaster โทรมาให้ช่วยคิดท่า retro สำหรับเติมไฟให้กับทีม (ใครอยากรู้บ้างยกมือขึ้น ^-^/) ก็เลยแชร์ที่นึกออกเร็ว ๆ ไปสองท่า หนึ่งในนั้นคือการโยงจาก boring tasks ไป purpose เริ่มจากให้สมาชิกแต่ละคนเอากระดาษ A4 แนวนอนมาแผ่นนึ

By Chokchai
ทำไมคนมีลูกถึกกันจัง?

ทำไมคนมีลูกถึกกันจัง?

ย้อนกลับไปปี 2013 มันเป็นเวลา 3 เดือนก่อนที่ผมจะตัดสินใจด้วยกันกับภรรยาว่าจะมีลูก แม่ยายคุยกับเราสองคนว่า… แม่ยาย: อายุก็เยอะขึ้นเรื่อยๆแล้วนะ ถ้าจะมี ก็ต้องมีตอนนี้แหละ ช้ากว่านี้ พอแก่ตัวไป มันจะมีผลกับพั

By Chokchai