Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to void* and back?

Tags:

c

c#

interop

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?

like image 685
mpen Avatar asked Aug 07 '13 06:08

mpen


2 Answers

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...
}
like image 74
Marc Gravell Avatar answered Sep 20 '22 13:09

Marc Gravell


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.

like image 36
Sriram Sakthivel Avatar answered Sep 20 '22 13:09

Sriram Sakthivel