本文介绍了从c#调用的c++ dll导出函数返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 C++ dll 导出函数返回一个字符串.我正在从 c# 调用这个函数.我在网上看到了很多例子,我真的很困惑该怎么做.

I am trying to return a string from a c++ dll export function. I am calling this function from c#. I have seen a lot of examples on the internet and I am really confused what to do.

我的 C++ 代码导出函数:

My c++ code to export function:

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

    char *cstr = new char[st.length() + 1];
    strcpy(cstr, st.c_str());
    return cstr;
}

当我尝试从 c# 调用此函数时:

When I try to call this function from c#:

[DllImport("\\SD Card\\ISAPI1.dll")]
private static extern string getDataFromTable(byte[] tablename);
static void Main(string[] args)
{
    string str = getDataFromTable(byteArray);
    Console.writeLine(str);
}

我在调用它时出错.我正在为 WinCE 6.0 创建这个

I got an error while calling it. I am creating this for WinCE 6.0

已编辑------------------------

EDITED------------------------

有没有类似的东西,我可以将一个空缓冲区从 c# 传递给 c++,c++ 函数将填充数据,我可以在 C# 中重用它

is there something like, i can pass a empty buffer to c++ from c# and c++ function will fill the data and i can reuse it in C#

推荐答案

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

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.

这篇关于从c#调用的c++ dll导出函数返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 06:12