开发者

.NET Interop and TR1 shared_ptr

开发者 https://www.devze.com 2023-01-12 13:39 出处:网络
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 i开发者_如何

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 i开发者_如何学JAVAt 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...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号