Returning pointers from unmanaged to managed code

前端 未结 1 739
感情败类
感情败类 2021-01-05 09:21

I\'ve an unmanaged dll that exports the folowing function:

SomeData* test();

Let\'s assume SomeData as:

typedef struct          


        
相关标签:
1条回答
  • 2021-01-05 09:50

    When declaring the managed function you need to match pointer types with reference values or IntPtr values. In this case the LPStruct modifier won't help. The easiest solution is to convert the return value of test to be an IntPtr rather than SomeData since the native method is returning a pointer value. You can then write the following wrapper

    [DllImport("DynamicLibrary.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr test();
    
    public static SomeData testWrapper() {
      var ptr = test();
      try {
        return (SomeData)Marshal.PtrToStructure(ptr, typeof(SomeData));
      } finally {
        // Free the pointer here if it's allocated memory
      }
    }
    
    0 讨论(0)
提交回复
热议问题