.NET 互操作和 TR1 shared_ptr
如何将非托管 C++ 代码中的共享指针封送到 C# 中?
我有一个 C++ 函数(通过 C 绑定公开),它将分配一个新的 MyObject 并通过共享指针返回指向它的指针。
在 C++ 中,我可以调用该函数:
MyObjHandle* ref = NULL:
GetMyObject(&ref); // double ptr...
MyObjHandle 的定义位置:
typedef struct obj_t {
shared_ptr<MyObject> objPtr;
} MyObjHandle ;
如何从 C# PInvoke 对 GetMyObject 的调用?显然,我只是定义了结构 MyObjectHandle,与 C# 中的情况几乎一样,只是我将成员 objPtr 定义为 IntPtr。结果惨遭失败,出现 AccessViolationException 错误。尝试了其他几个 PInvoke 变体,但也失败了。我似乎找不到任何带有shared_ptr 和C# 的互操作示例。任何帮助表示赞赏...
How is it possible to marshal a shared_ptr from unmanaged C++ code into C#?
I have a function in C++ (exposed through C bindings) that will allocate a new MyObject and return a pointer to it via a shared_ptr.
In C++ I can call the function:
MyObjHandle* ref = NULL:
GetMyObject(&ref); // double ptr...
where MyObjHandle is defined:
typedef struct obj_t {
shared_ptr<MyObject> objPtr;
} MyObjHandle ;
How would I PInvoke the call to GetMyObject from C#? I did the obvious of just defining the structure MyObjectHandle pretty much as is in C# expcept I defined the member objPtr as an IntPtr. That failed miserably with a AccessViolationException error. Tried a couple other PInvoke variations which also failed. I can't seem to find any interop samples with shared_ptr and C#. Any help appreciated...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只能在 C# 中将 MyObjHandle 作为 IntPtr 进行检索。您将永远无法访问结构中的内部 objPtr。 pinvoke 签名应如下所示:
// 根据需要调整返回类型
[DllImport(...)]
int GetMyObject(out IntPtr pMyObjHandle);
然后,您可以将 pMyObjHandle 传递回任何其他需要 MyObjHandle* 作为参数的 pinvoke 方法。
You can only retrieve the MyObjHandle as an IntPtr in C#. You will never have access to the internal objPtr within the structure. The pinvoke signature should look like:
// adjust return type as needed
[DllImport(...)]
int GetMyObject(out IntPtr pMyObjHandle);
You can then pass the pMyObjHandle back into any other pinvoke methods expecting a MyObjHandle* as the parameter.