Convert object to void * and vice versa?

I am trying to write a wrapper around a C function that expects a function pointer and arbitrary user data ( void* ). Function pointer I figured out how to deal with the use of delegates, but I can't figure out how to convert an object to void* .

I can do this a ref object , because it behaves like an AFAIK pointer, but when I try to do this, I get an exception, for example

An invalid VARIANT was detected during the conversion from an unmanaged VARIANT to a managed entity. Transferring invalid VARIANTs to the CLR may cause unexpected exceptions, corruption, or data loss.

This "solution" may work for me, but I decided that there should be a way to pass arbitrary data to the C DLL so that it can be passed back later?

+6
source share
2 answers

Personally, I would suggest using struct here, which is much more applicable for what you are trying to do (plus you can customize the internal layout if you need to). For example, with struct Foo and a field of 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 should not even 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... } 
+2
source

If I'm not mistaken, I think you need the Pointer.Box and Pointer.UnBox . These methods help insert and delete an unmanaged pointer. Check out Pointer.Box and Pointer.UnBox in msdn.

+2
source

Source: https://habr.com/ru/post/951192/


All Articles