通过引用将结构从托管代码传递给非托管代码?

时间:2013-05-13 19:45:40

标签: c# c memory unmanaged managed

我的结构在c代码中看起来像这样:

typedef struct _REQUEST {
    char D [_D_MAX+1];
    char M [_M_MAX+1];
    char T [_T_MAX+1];
    char ClRef [_CL_REF_MAX+1];
    char load [_LOAD_MAX];
    ULONG loadLen;
} _REQUEST, *LP_REQUEST;

在c#中就像这样:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct _REQUEST_STRUCT {
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string D;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string M;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string T;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
    public string clRef;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1200)]
    public string Load;

    public UInt32 LoadLen;
}

我调用的方法在c:

中是这样的
int 
AJ_STDCALL 
SimpTran (const char* svc_name, 
                   const LP_REQUEST query, 
                   LP_RESPONSE      response)
{
    //init stuff
    //Validate input parameters
    if ( query == NULL )
        return(ERR_QUERY_NULL);

    if (query->loadLen == 0)
        return (ERR_QUERY_NULL);
}

在c#中:

[DllImport(LINUXLIB, CallingConvention = CallingConvention.StdCall)]
public static extern int SimpTran(string serID, ref _REQUEST_STRUCT request, out IntPtr response);

我称之为:

p_request_struct = new _REQUEST_STRUCT();
// fill p_request_struct

// response
p_response_struct = new _RESPONSE_STRUCT();

// initialize unmanaged memory to hold return struct
IntPtr ptrRet = Marshal.AllocHGlobal(Marshal.SizeOf(p_response_struct));
Marshal.StructureToPtr(p_response_struct, ptrRet, false);

iRet = SimpTran(SerID, ref p_request_struct, out ptrRet);

我得到空查询!在C代码中,query==nulltrue,它返回null。但我填充请求结构?

我是否也必须为此分配内存?

0 个答案:

没有答案