Function Pointer WINAPI - c

I need help with the code below.
typedef TP_StatusType ( WINAPI * TP_UserSelectPathType )( TP_InterfaceType* anInterface, UINT32* aReturnPathId, TP_Path* aReturnPath );
extern TP_UserSelectPathType TP_UserSelectPath;
locRouterDll = LoadLibraryA( aDllFileName );
TP_UserSelectPath = (TP_UserSelectPathType)GetProcAddress( locRouterDll, "TP_UserSelectPath" );
TP_StatusType eStatus;
eStatus = TP_UserSelectPath( &eInterface, &lPathId, &xPathHandle );
Which function is called in the last line?

Which function is called in the last line?
Well, TP_UserSelectPath is a function pointer variable that is assigned the function pointer returned by the call to GetProcAddress. So
TP_UserSelectPath(...)
calls the function named TP_UserSelectPath that is exported by the module locRouterDll. This is a function that is external to your code. The function is implemented in the module locRouterDll which was loaded into your process dynamically at runtime by the call to LoadLibraryA.
If this is all brand new to you then you should start by reading the Dynamic-Link Libraries topic on MSDN.

TP_UserSelectPath is called because you are assigning the return value of TP_UserSelectPath with the following parameters &eInterface, &lPathId, &xPathHandle to eStatus

Related

Verify function pointer equality with Cmockery

I am writing Unit test and wondering how would I test function pointers with Cmockery.
A.c
void (*FunctionPtr)(void) = &funcA;
void funcA()
{
// calls func B
funcB();
}
TestA.c
void Test_A( void ** state )
{
// test for FunA; working as expected
}
void Test_FunctionPtr( void** state )
{
// how to check here that FunctionPtr holds memory location of funcA?
// I tried something like below:
assert_memory_equal( FunctionPtr, funcA(), sizeof( funcA() ) );
}
During runtime I am getting error and I have no clue how to resolve that. May be I using wrong API to assert but don't know which one to call.
Below is my error:
error during runtime:
Test_FunctionPtr: Starting test
No entries for symbol funcB.
funcA() calls the function. You want a pointer to the function, which is funcA or &funcA (does not make a difference which one you use: read here).
Also you want to compare the value saved in FunctionPtr with the address of funcA. You do not want to compare the memory where FunctionPtr points to with the function.
So instead of assert_memory_equal( FunctionPtr, funcA(), sizeof( funcA() ) ); I would use assert(FunctionPtr == funcA);
You wrote in your comment that you are using assert_int_equal now. Note that both values are not int, so if the macro uses printf with %d (or similar) in an error case you are invoking undefined behaviour.

How can I use global variables used between two C function which are called in Modelica?

I have two function definitions in C which share some global variables. I want to call these functions in Modelica but I do not know how can I correctly keep the value of the global variable between two function calls.
file.c
/*Global variable definition*/
int* global_test1;
void FirstFunc (const int* init_value){
memcpy(global_test1, init_value, 2*sizeof(int));
}
void SecondFunc(int* some_output_variable){
memcpy(some_output_variable, global_test1, 2*sizeof(int));
}
calling_FirstFunc.mo
function calling_FirstFunc
input Integer[2,1] init_value = [3;3];
external "C" FirstFunc(init_value);
end;
calling_SecondFunc.mo
function calling_SecondFunc
output Integer[2,1] output_var;
external "C" SecondFunc(output_var);
end;
model.mo
model Calling_TwoFuncs
Integer[2,1] input_var = [3;5];
Integer[2,1] output_var;
equation
calling_FirstFunc(input_var);
when time>5.0 then
output_var = calling_SecondFunc();
end when;
end Calling_TwoFuncs;
Your sample code should almost work correctly. The C-functions will keep their state and work fine if (and only if) they are called in the order First, Second. You also need to allocate memory for global_test1... But this order is not guaranteed in the code. I suggest using external objects instead; then you can create multiple instances of the same model and not have a global state in the C-code (because you can malloc memory and return this for the constructor call; the First call). Note that you should probably pass the size of the vector to the constructor in order to be more general.

Function callback from C to Swift

I have this C function that simply calls back another function passed as a parameter
void call_my_function(void (*callback_function)())
{
callback_function();
}
This is C test code:
void func_to_call() // a simple test function passed in as a callback
{
printf("function correctly called");
}
void test() // entry point
{
void (*foo)();
foo = &func_to_call;
call_my_function(foo); // pass the address of "func_to_call()" to "call_my_function()"
}
Essentially, from test(), I call call_my_function() passing in the address of func_to_call(), and then call_my_function() calls back func_to_call().
From swift I see correctly the functions test() and func_to_call(), but it seems that
void call_my_function(void (*callback_function)())
is not recognized (use of unresolved identifier)
If I remove the parameter void (*callback_function)() then the function is recognized again.
What can I do to pass a Swift function address to C and have it called back? Is it possible?
Thanks
Apple confirmed me, on the dev forum, that it is not supported now, and requested me to fill a new request on the bugreporter.
Moreover, I give to the readers another detail:
It seems that in the compiled binary the symbols for all swift functions are already available and bridged to be accessible from C (even in a swift-only app)
I made an app called FunctionTest, iPhone App with this function in a swift file
func thisIsATestFunction()
{
println("test")
}
compiled, and then from Terminal:
nc /Users/xxx/Library/Developer/Xcode/DerivedData/FunctionTest-hhrbtzsuyrdoftfnbakosvenaiak/Build/Products/Debug-iphonesimulator/FunctionTest.app/FunctionTest
U _NSStringFromClass
U _OBJC_CLASS_$_NSString
U _OBJC_CLASS_$_UIResponder
U _OBJC_CLASS_$_UIViewController
U _OBJC_CLASS_$_UIWindow
000088c8 S _OBJC_CLASS_$__TtC12FunctionTest11AppDelegate
00008888 S _OBJC_CLASS_$__TtC12FunctionTest14ViewController
.........
.........
00003840 T __TF12FunctionTest19thisIsATestFunctionFT_T_ <--- this is my test function
Calling from c the address 00003840 executed the function
void (* func)() = 0x00003840;
func(); // the swift function is executed
So I think that this is already work-in-progress...hoping that they will implement this functionality in the next releases :-)

Convert C Code to Delphi

I need to convert this Line from C to Delphi.
Int CALLBACK EXPORT EXAMPLEFUNCTION(VOID){
SETEVENT(hasync);
Return Success;
}
Please i need some help.
thanks ;)
Kind of guessing here, because the style's really messy, but I think that would translate something like this:
const Success = 1; //or whatever; might not be 1.
//assume a const definition for a value
//called Success exists somewhere in scope
function EXAMPLEFUNCTION(): integer; stdcall; //CALLBACK = stdcall calling convention
begin
SETEVENT(hasync); //hopefully this makes sense in context
result := Success;
end;
That's the best I can do without further context. The EXPORT declaration is a preprocessor macro, and it (probably) means that this is part of a DLL and that this is a function that's supposed to be callable by programs that load the DLL. In Delphi, that's not part of the function definition; instead, you put it in an exports clause.

callbacks inside a DLL?

I have a callback inside a C DLL (static void __stdcall) . I want another program to register it as such (by passing it the func ptr) and then call the calback inside the DLL. I have had no luck so far. However, the same callback works if its inside a regular C++ program. I am now wondering if having callbacks in a DLL is even possible. Any help will be appreciated!
Thanks.
Adding some code:
C# app:
[DllImport("DLLfilename.dll")]
public static extern void DLL_SetCallback(CallbackDelegate pfn);
public delegate void CallbackDelegate();
//setDelegate() is called in init() of the C# app
public void setDelegate()
{
CallbackDelegate CallbackDelegateInstance = new CallbackDelegate(callback);
DLL_SetCallback(CallbackDelegateInstance);
}
public void callback()
{
//This is the function which will be called by the DLL
MessageBox.Show("Called from the DLL..");
}
C DLL:
//is linked to externalLibrary.lib
#include "externalLibrary.h"
typedef void (__stdcall CallbackFunc)(void);
CallbackFunc* func; //global in DLL
//Exported
extern "C" __declspec(dllexport) void DLL_SetCallback(CallbackFunc* funcptr)
{
//setting the function pointer
func = funcptr;
return;
}
//Exported
extern "C" __declspec(dllexport) void RegisterEventHandler(Target, Stream,&ProcessEvent , NULL)
{
//ProcessEvent is func to be caled by 3rd party callback
//Call third-party function to register &ProcessEvent func-ptr (succeeds)
...
return;
}
//This is the function which never gets called from the 3rd party callback
//But gets called when all the code in the DLL is moved to a standard C program.
void __stdcall ProcessEvent (params..)
{
//Do some work..
func(); //Call the C# callback now
return;
}
Your question is a little confusing. Are you saying that you have a non-exported function within a DLL, which you wish to take the address of and pass to some external code, which will call it back? That's perfectly reasonable to do. If it's not working, here are the things to look at.
1) Make sure that the calling convention is correct on the definition of the function, the type of the function pointer within your DLL, and the type of the function pointer as declared in the external code.
2) Within your DLL, attempt to call the callback through the same function pointer that you're passing to the external code.
3) If (1) is correct, and (2) works, then fire up your debugger, put a breakpoint on the line where you're trying to call the callback from external code, and then drop into disassembly. Step through the call and see where it ends up.

Resources