0

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!

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
HypeZ
  • 4,017
  • 3
  • 19
  • 34
  • 1
    possible duplicate of [PInvoke C#: Function takes pointer to function as argument](http://stackoverflow.com/questions/5235445/pinvoke-c-function-takes-pointer-to-function-as-argument) – clcto Sep 30 '14 at 15:34
  • Because i didn't know how to pass a function pointer as a parameter, so a struct "looked" fine! I think the question marked as duplicate can really solve my problem, i'm doing some test – HypeZ Sep 30 '14 at 15:42

1 Answers1

3

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);
jbriggs
  • 353
  • 2
  • 10
  • this looks good, but how can i define what "GenericFunction" does? I need to declare with a sort of delegate? – HypeZ Sep 30 '14 at 15:48
  • @HypeZ Just as you would use other delegates. Create a function with the same signature and pass the name of that function to the `NativeFunction` – clcto Sep 30 '14 at 15:55