[英]PInvoke - How to marshal for 'SomeType* []'?
我有一個本地庫,其中包含一些本機ntype
,並希望在其中調用一些函數。
我能夠為:
foo1(ntype** p) ==> foo1(IntPtr[] p)
但不知道如何做到:
foo1(ntype*[] p) ==> foo1(<???> p)
至少IntPtr[]
沒有用。
編輯
我試圖編組的非托管函數是:
extern mxArray* mclCreateSimpleFunctionHandle(mxFunctionPtr fcn);
其中mxFunctionPtr
是:
typedef void(*mxFunctionPtr)(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
這表示調用以下matlab函數簽名:
function [varargout] = callback(varargins)
%[
%% Do callback code %%
%]
顯然,從我的期望來看,這個函數指針應該為我提供了2個mxArray*
列表:
目前來自我所做的測試,它只返回第一個plhs
mxArray*
在plhs
和prhs
列表中
首先要做的是將您的原生ntype
轉換為托管struct
。
例如:
public struct Ntype
{
public int Field1;
public long Field2;
}
然后在C#代碼中使用簡單的IntPtr
參數定義方法。
[DllImport]
static void foo1(IntPtr myParam);
最后,這是你如何使用它:
IntPtr buffer = IntPtr.Zero;
try
{
// Allocates a buffer. The size must be known
buffer = Marshal.AllocHGlobal(0x1000);
// Call to your unmanaged method that fills the buffer
foo1(buffer);
// Casting the unmanaged memory to managed structure that represents
// your data
Ntype obj = (Ntype)Marshal.PtrToStructure(buffer, typeof(Ntype));
}
finally
{
// Free unmanaged memory
if (buffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(buffer);
}
}
得到它了
在' SomeTime* []
'中正確編組:
extern mxArray* mclCreateSimpleFunctionHandle(mxFunctionPtr fcn);
typedef void(*mxFunctionPtr)(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[]);
是:
// For function pointer
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate void MCRInteropDelegate(int nlhs,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysInt, SizeParamIndex = 0)][Out] IntPtr[] plhs,
int nrhs,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysInt, SizeParamIndex = 2)][In] IntPtr[] prhs);
// For API function
[DllImport(DLLNAME, EntryPoint = "mclCreateSimpleFunctionHandle", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr _mclCreateSimpleFunctionHandle(MCRInteropDelegate fctn);
說明
MarshalAs
屬性指示將SomeTime*[]
LPArray
為IntPtr
的LPArray
,其中數組的大小由函數的參數包含在零SizeParamIndex
引SizeParamIndex
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.