C code passing a pointer to a function to a C# .Net object?

T

TN

I have a bit of C code, that creates an instance of a .Net class that
has been built as a type library. Everything is working as expected, I
can pass strings to methods in the object. What I would like to also do
is pass a pointer to C function to one method to store it as a callback,
then later have another method call that callback. I know this is not a
"safe" operation, but I am wondering if it can be done. If not what
other methods do I have to implement a callback to C code from a .Net
class that is a type library?
Thanks much.
 
W

Willy Denoyette [MVP]

|I have a bit of C code, that creates an instance of a .Net class that
| has been built as a type library. Everything is working as expected, I
| can pass strings to methods in the object. What I would like to also do
| is pass a pointer to C function to one method to store it as a callback,
| then later have another method call that callback. I know this is not a
| "safe" operation, but I am wondering if it can be done. If not what
| other methods do I have to implement a callback to C code from a .Net
| class that is a type library?
| Thanks much.

Pass the function pointer to .NET as a long on 32 bit OS, as a long long on
64 bit.

C++
static void CALLBACK CallbackProc(args..)
{
......
}

....
obj->SomeCOMMethod(reinterpret_cast<long>(CallbackProc));


C#

delegate void Proc(args..);

SomeCOMMethod(IntPtr fPtr)
{
...
Proc p = (Proc)Marshal.GetDelegateForFunctionPointer(fPtr,
typeof(Proc));
p(...); // Call CallBackProc
....

Willy.
 

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