I'm trying to write a wrapper around a C function that expects a function pointer and arbitrary user data (void*
). The function pointer I've figured out how to deal with using delegates, but I can't figure out how to convert an object
into a void*
.
I can make it a ref object
instead, since that behaves like a pointer AFAIK, but when I try that I get an exception like
An invalid VARIANT was detected during a conversion from an unmanaged VARIANT to a managed object. Passing invalid VARIANTs to the CLR can cause unexpected exceptions, corruption or data loss.
This "solution" might work for me, but I figured there has to be a way to pass arbitrary data to a C DLL so that it can be passed back later?
Personally, I would advise using a struct
here, which is much more applicable for what you are trying to do (plus you can tweak the internal layout if you need). For example, with a struct Foo
, and a field on a reference-type foo
:
unsafe void Bar()
{
fixed (Foo* ptr = &foo) // here foo is a field on a reference-type
{
void* v = ptr; // if you want void*
IntPtr i = new IntPtr(ptr); // if you want IntPtr
// use v or i here...
}
}
Note: if foo
is a local variable, then it is on the stack and doesn't even need to be fixed
:
unsafe void Bar()
{
Foo foo = new Foo();
Foo* ptr = &foo; // here foo is a local variable
void* v = ptr; // if you want void*
IntPtr i = new IntPtr(ptr); // if you want IntPtr
// use v or i here...
}
If am not mistaken I think you need Pointer.Box
and Pointer.UnBox
methods.
These methods help to box and unbox the unmanaged pointer.
Check out Pointer.Box and Pointer.UnBox at msdn.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With