Convert object to void* and back?

喜欢而已 提交于 2019-12-23 09:30:04

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18096415/convert-object-to-void-and-back

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!