且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从c#调用的c++ dll导出函数返回字符串

更新时间:2023-02-12 16:11:37

这个怎么样(注意,它假定正确的长度 - 你应该传入缓冲区长度并防止溢出等):

How about this (Note, it assumes correct lengths - you should pass in the buffer length and prevent overflows, etc):

extern "C" __declspec(dllexport)  void  __cdecl getDataFromTable(char* tableName, char* buf)
{
    std::string st = getDataTableWise(statementObject, columnIndex);
    printf(st.c_str()); 

    strcpy(buf, st.c_str());
} 

然后在 C# 中:

[DllImport("\\SD Card\\ISAPI1.dll")]
private static extern string getDataFromTable(byte[] tablename, byte[] buf);
static void Main(string[] args)
{
    byte[] buf = new byte[300];
    getDataFromTable(byteArray, buf);
    Console.writeLine(System.Text.Encoding.ASCII.GetString(buf));
}

注意,这确实对 C++ 应用程序中的字符编码不是 unicode 做出了一些假设.如果它们是 unicode,请使用 UTF16 而不是 ASCII.

Note, this does make some assumptions about character encodings in your C++ app being NOT unicode. If they are unicode, use UTF16 instead of ASCII.