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


G

Guest

Hi,

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
this.

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

and the C# code
...in project
public delegate void Callback(int x, int y, int z);

....in main
Callback ArpCallback = new Callback(Form1.tempFunc);
ResponseFunc(ArpCallback);

....import
[Dllimport("dllfile.dll")]
static extern int ResponseFunc (int x, int y, int z);

....other functions
int tempFunc ( int a, int b, int c){
Console.WriteLine("hello");
}

This errors on the ResponseFunct(ArpCallback) portion in a
System.NotSupportedException.

It's starting to get really frustrating so if anyone can help me that'd be
great...
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.

Thanks!
 
Ad

Advertisements

N

Nicholas Paldino [.NET/C# MVP]

Mitchell,

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:

[DllImport("dllfile.dll")]
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

Top