HypeZ
HypeZ

Reputation: 4127

Wrap c++ function that needs function pointer

i have an external dll (with C++ documentation on how to use it) and i need to use some functions inside of it from my C# program.

I wrote a little wrapper for some functions and they works well, but i don't know how to wrap functions that needs function pointer as parameter.

C++ documentations says:

uint NativeFunction(uint32 parameter, GenericFunction *func)

Since GenericFunction should get 2 *char as parameters i wrote this in C#:

public struct GenericFunction 
{
    public string param1;
    public string param2;
}

[DllImport("externalLib.dll", SetLastError = true)]
public static extern uint NativeFunction(uint parameter, GenericFunction func);

And when i need to call it i use

GenericFunction test = new GenericFunction();
uint result = NativeFunction(0u, test);

with this i have this ugly error:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I'm pretty sure i'm calling the function in a wrong way since i still have to define what GenericFunction do, but i have no idea how to do it and google is not helping me this time!

Upvotes: 0

Views: 456

Answers (1)

jbriggs
jbriggs

Reputation: 353

You can use delegates in place of a function pointer.

public delegate void GenericFunction(string param1, string param2);

[DllImport("externalLib.dll", SetLastError = true)]
public static extern uint NativeFunction(uint parameter, [MarshalAs(UnmanagedType.FunctionPtr)]GenericFunction func);

Upvotes: 3

Related Questions