Passing function pointers to a unmanaged c++ dll from c#




I have code from a previous project that I've packaged into a dll in c++.
I'm now trying to call functions within that c++ dll from my c# code.

I've managed to get it to work for ints and other basic types but now I'm
trying to pass a pointer to a function but I can't figure out a way to do

So far I have a function in my c++ code:
int ResponseFunc(void (*callback)(int, int, int));

and the C# code project
public delegate void Callback(int x, int y, int z); main
Callback ArpCallback = new Callback(Form1.tempFunc);

static extern int ResponseFunc (int x, int y, int z);

....other functions
int tempFunc ( int a, int b, int c){

This errors on the ResponseFunct(ArpCallback) portion in a

It's starting to get really frustrating so if anyone can help me that'd be
the general synopsis of what I'm looking for is that I want to call my
function in my c++ dll, from my c# program, with a pointer to a function in
the c# code.




Nicholas Paldino [.NET/C# MVP]


When you define your ResponseFunc, you need to declare the callback type
as a delegate type. The marshaler will take care of the rest. So, your
definition for ResponseFunc should be:

static extern int ResponseFunc(Callback callback);

Hope this helps.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question