1

这是我需要解决的一个简单问题,但它让我觉得我的头发变白了,因为我所有的尝试都返回了同样的错误:

“试图读取或写入受保护的内存。这通常表明其他内存已损坏。”

我有一个用 C++ 编写的示例应用程序,它调用 dll。以下是相关代码:

    //function I need to call
bool convertHKID_Name(char *code,RECO_DATA *o_data);    //hkid 

//struct definition
struct RECO_DATA{
    wchar_t FirstName[200];
    wchar_t Surname[200];
};

//how it is used in C++ code
CString code;
RECO_DATA data;
GetDlgItemText(IDC_CODE,code);
char _code[200];
WideCharToMultiByte(CP_UTF8, 0, code, -1, (char *)_code, 200, NULL, NULL);
ocr->convertHKID_Name(_code,&data)

现在,当我调试 C++ 代码时,它会做正确的事情——将一些 Unicode 数据写入数据结构。

这是我尝试在 C# 中做同样的事情

    //my C# wrapper class
public class cnOCRsdk
{
    [StructLayout(LayoutKind.Sequential, Size=400, CharSet=CharSet.Unicode), Serializable]
    public struct RECO_DATA
    {
        [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 200)]
        public string FirstName;
        [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 200)]
        public string Surname;
    };

    [DllImport(@"cnOCRsdk.dll", CharSet=CharSet.Auto, EntryPoint = "?convertHKID_Name@CcnOCRsdk@@QAE_NPADPAURECO_DATA@@@Z")]
    public static extern bool convertHKID_Name(ref string num, ref RECO_DATA o_data);

    [DllImport("Kernel32.dll")]
    public static extern int WideCharToMultiByte(uint CodePage, uint dwFlags,
        [In, MarshalAs(UnmanagedType.LPWStr)]string lpWideCharStr,
        int cchWideChar,
        [Out, MarshalAs(UnmanagedType.LPStr)]StringBuilder lpMultiByteStr,
        int cbMultiByte,
        IntPtr lpDefaultChar, // Defined as IntPtr because in most cases is better to pass
        IntPtr lpUsedDefaultChar // NULL
        );
}

//my attempt to call the function from the dll
cnOCRsdk.RECO_DATA recoData = new cnOCRsdk.RECO_DATA();
string num = "262125355174";
StringBuilder sb = new StringBuilder(200, 200);
cnOCRsdk.WideCharToMultiByte(65001, 0, num, -1, sb, 200, IntPtr.Zero, IntPtr.Zero);
string sbTostring = sb.ToString();
//the next line generates the 'Attempted to read or write protected memory' error
bool res = cnOCRsdk.convertHKID_Name(ref sbTostring, out recoData);

我的猜测是我没有正确编组 RECO_DATA 结构,因为 convertHKID_Name 函数写入的正是这个结构。但是我应该如何解决它?

4

2 回答 2

2

我相信它应该工作,如果你

  1. 将声明更改 convertHKID_NameCharSet.Ansi
  2. Remove the "ref" from the string parameter
  3. Pass the string num directly to convertHKID_Name instead of calling WideCharToMultiByte
于 2009-03-25T03:19:49.487 回答
0

I wrote a managed wrapper in C++ for my unmanaged dll, but got stuck a bit again.

Continued here

Passing C# data type parameters to dll written in C++?

于 2009-03-26T01:07:48.877 回答