简体   繁体   中英

Calling function in C dll from C# which returns somekind of pointer to function pointer

I have an dll written in C (no access to the source code) which I wish to call from C#. If the dll used simple types I would know how to handle it via PInvoke, but it doesn't :(

The function in the dll I'm trying to call takes no parameters so the problem is how to handle the return. I have some example C code which calls the function which I liked to recreate in C#. As I understand it the return type is a pointer to a function pointer, is this correct? The return from the function should also later be passed back to other functions in the dll.

Any help is greatly appreciated :)

/* C code */
typedef const struct simModel* (*ModelFunc)(void);
int ret=0;
HINSTANCE hInst = 0;
ModelFunc f=0;
const struct simModel*model =0;
if (!(hInst=LoadLibrary("model.dll"))) {
    return 1;
}
if (!(f=(ModelFunc)GetProcAddress(hInst,"simModelFunctions"))) {
    ret=1;
} else if (!(model=f())) {
    ret=1;
} else {
    /* Do stuff */
}

The simModelFunctions function returns a pointer to simModel structure (a data type).

The code you show calls the function by finding its address dynamically, which is why it has a function pointer. This pointer does not come from the function itself.

In C# you can simply declare it with DllImport from model.dll. Eg

[DllImport("model.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
private static IntPtr simModelFunctions();

Then you can use Marshal.PtrToStructure if you need to examine the contents of the structure, or just pass the returned IntPtr to other functions without bothering what's inside.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM