0 0

C#调用C++的DLL传结构体指针参数,尝试读取或写入受保护的内存,这通常指示其他内存已损坏。怎么解决啊25

C++结构体
typedef struct tagtmcp_login_info
{
    int ip_type;
    int user_id;
    int error_code;
    int control_uint_id;
    int privilege_code_size;
    int* privilege_code_array;
    char session_id[128];
    bool login_result;
    int userRightLevel;
 
    tagtmcp_login_info()
    {
        privilege_code_array = NULL;
        login_result = false;
    }
 
    ~tagtmcp_login_info()
    {
        if(privilege_code_array)
            delete [] privilege_code_array;
    }
 
}tmcp_login_info, *ptmcp_login_info;

C#结构体
[StructLayout(LayoutKind.Sequential)]
    public struct tmcp_login_info
    {
        public int ip_type;
        public int user_id;
        public int error_code;
        public int control_uint_id;
        public int privilege_code_size;
        public int[] privilege_code_array;
        public string session_id;
        public bool login_result;
        public int userRightLevel;
    }

C++函数定义
TMCP_INTERFACE_SDK_API(int) tmcp_login_cms(const char* user_name, 
                                           const char* password, 
                                           tmcp_enum_login_types login_type, 
                                           ptmcp_login_info plogin_info,
                                           const char* end_point_url,
                                           const char* local_ip = NULL);

C#调用
[DllImport("tmcp_interface_sdk.dll", EntryPoint = "tmcp_login_cms", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        private extern static int tmcp_login_cms(string user_name, string password, int login_type, IntPtr plogin_info, string end_point_url, string local_ip);
 
        public static int call_tmcp_login_cms(string user_name, string password, int login_type, ref tmcp_login_info info, string end_point_url, string local_ip)
        {
            Type type = info.GetType();
            int size = Marshal.SizeOf(type);
            IntPtr pBuff = Marshal.AllocHGlobal(size);
            int ret = tmcp_login_cms(user_name, password, login_type, pBuff, end_point_url, local_ip);
            IntPtr ptr = new IntPtr(pBuff.ToInt64() + size);
            Marshal.FreeHGlobal(pBuff);
            tmcp_login_info plogin_info = (tmcp_login_info)Marshal.PtrToStructure(ptr, type);/*这行代码报错*/
            return ret;
        }
 
调用代码:
tmcp_login_info info = new tmcp_login_info();  
call_tmcp_login_cms("admin", "12345", 0, ref info, "", "");

出错信息:
“System.AccessViolationException”类型的未经处理的异常出现在 mscorlib.dll 中。
其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
2014年9月19日 10:26

1个答案 按时间排序 按投票排序

0 0

楼主您好,我也遇到一样问题,您怎么解决的呢?

2018年3月23日 09:42

相关推荐

Global site tag (gtag.js) - Google Analytics