0

我的结构在 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。但是我正在填充请求结构?

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

4

0 回答 0