代码之家  ›  专栏  ›  技术社区  ›  subbu

将一个字符串变量作为一个介于C++的DLL和C++ DLL之间的REF

  •  4
  • subbu  · 技术社区  · 16 年前

    我有一个dll和一个C++ dll。我需要传递一个字符串变量作为引用从C到C++。我的C++ DLL将用数据填充变量,我将在C中使用它。我试过使用ref。但是我的c dll抛出了异常。“试图读取或写入受保护的内存。…这通常表明其他内存已损坏”。你知道怎么做吗

    2 回复  |  直到 16 年前
        1
  •  3
  •   Brian R. Bondy    16 年前

    作为一般规则 StringBuilder 作为参考值或返回值 string 对于不希望/不需要在dll中更改的字符串。

    字符串拼接 对应于 LPTSTR 一串 对应于 LPCTSTR

    C函数导入:

    [DllImport("MyDll.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static void GetMyInfo(StringBuilder myName, out int myAge);
    

    C++代码:

    __declspec(dllexport) void GetMyInfo(LPTSTR myName, int *age)
    {
        *age = 29;
        _tcscpy(name, _T("Brian"));
    }
    

    调用函数的C代码:

    StringBuilder name = new StringBuilder(512);
    int age; 
    GetMyInfo(name, out age);
    
        2
  •  1
  •   munissor    16 年前

    将一个固定大小的StringBuilder从C到C。