转换对象为void *和回来? [英] Convert object to void* and back?

查看:287
本文介绍了转换对象为void *和回来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写围绕期望一个功能的 C函数包装指针和任意的用户数据(无效* )。函数指针我已经想通了如何处理使用委托,但我无法弄清楚如何转换对象无效*

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

我可以把它 REF对象来代替,因为这就像一个指针,据我所知,但是当我尝试,我得到这样

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

从非托管VARIANT到托管对象的转换过程中,检测到无效VARIANT。传递无效变种的CLR会导致意外的异常,损坏或数据丢失。

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.

该办法可能为我工作,但我想必须有传递任意数据的方法一个C DLL,以便它可以在以后传递回

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

这篇关于转换对象为void *和回来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆