English 中文(简体)
从无效*改为C#
原标题:Conversion from void* to object in C#

In a C# project, I need to pass object parameters by putting references in a structure. i.e. I have a structure passed to a dispatcher

struct SOMESTRUCT
{
    public int lpObject;
}

1. 标有一对一等习俗物体的点

class SomeClass
{
    private string foo;
}

而SOMESTRUCT的结构则从方法转向方法,最终达到我的准则。 我不能改变处决流程或奇怪的SOMSTRUCT系统,因此,我猜测,唯一的解决办法是把我的反对放在这样一个点上:

var myObject = new SomeClass();
GCHandle GC = GCHandle.Alloc(myObject, GCHandleType.Pinned);
int myRef = GC.AddrOfPinnedObject().ToInt32();
GC.Free();

SOMESTRUCT struct;
struct.lpObject = myRef;
someMethod(struct);

然而,我可以说明如何从野外收回我的野心成员。 与此类似:

SomeClass myObject = CastPointerToObject(struct.myRef) as SomeClass;

是否有办法这样做? 我怎么能告诉垃圾收集器处理物体? 我是否应当建立一个新的垃圾收集物体,并按实地复制数据领域?

TYIA,

最佳回答

页: 1

......

struct SOMESTRUCT
{
    public SomeClass object_ref;
}

它是在结构中储存参考资料的正确方式。

你撰写的法典和公认的答案是100%的破碎。

由<代码>GC.AddrOfPinatedObject(GCHandle)退回的地址在<代码>上仍然有效。 GCHandle is intact. 不得打上<代码>GCHandle。 免费,不得让<代码> 收集了GCHandle。 在你的法典中,这一地址在你储存时已经毫无意义。

但是,你们应该让步。 该网络采用不同的参考类型,在垃圾收集过程中对点人进行管理。 那么,你就不必跳跃。 处理受管制物体的唯一原因是,该物体在返回后将转至现有的本地的DL职能,从而节省点名。 例如,它需要有开放的GL缓冲阵列。 在使用其他C#方法时,NOT是必要的。

如果SOMESTRUCT实际上是一种当地数据类型,由一些DL公司使用,那么,你需要确保保持<代码>GCHandle。 只有当<代码>GCHandle存在时,你才能继续有效。

问题回答

你们是否希望把返回点回落到一个结构中?

类似:

lvHitTestInfo = (LVHITTESTINFO)Marshal.PtrToStructure(lP, typeof(LVHITTESTINFO));

如果将Halit 试验Info 定为一种结构和点。

或者,我没有正确理解你的问题。 或许可以解释更多(更完整的法典样本)。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签