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!

2
  • 1
    possible duplicate of PInvoke C#: Function takes pointer to function as argument Commented Sep 30, 2014 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 Commented Sep 30, 2014 at 15:42

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

this looks good, but how can i define what "GenericFunction" does? I need to declare with a sort of delegate?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.