gpt4 book ai didi

c# - 将 C++ 字符返回到 C#

转载 作者:行者123 更新时间:2023-11-30 02:05:50 25 4
gpt4 key购买 nike

我有一个 C++ 项目,我必须在其中将一些变量从 C++ 返回到 C#。

这些 char 变量在主程序中:

char test1[MAX_Q_LEN], test2[MAX_Q_LEN], test3[MAX_Q_LEN];

在我的 C 程序中完成对这些变量的处理后,我必须在 C# 程序中返回这些变量的值。

ReturnChar.h

extern "C" RETURNCHAR_API TCHAR* __cdecl testString();

ReturnChar.cpp

extern "C" RETURNCHAR_API TCHAR* testString()
{
return ;
}

TestImport C#

static class TestImport
{
[DllImport("MyDLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr testString();
}


public partial class MainWindow : Window
{
public MainWindow()
{
try
{
InitializeComponent();
textBox1.Text = ReturnSomething()
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private static string ReturnSomething()
{
IntPtr t = TestImport.testString();
String result = Marshal.PtrToStringAuto(t);
}

我尝试了上述方法,但无法找到返回上述 char 值的方法。此外,这不应该是一个独立的函数,因为只有在执行 main 函数后才能获取值,这将为这些变量提供正确的值。

有什么建议吗?

最佳答案

我会建议一个解决方案,要求您将函数签名更改为:

extern "C" int __cdecl testString(char *output, int outputSize);

也就是说,将分配的缓冲区作为第一个参数传递给将保存输出的函数,并将缓冲区的大小作为第二个参数传递。

请注意,我将函数的返回类型称为 int。这是因为您可以从函数返回输出实际 大小,并且调用者可以解释此值以确认outputSize 值足够大以容纳输出字符串。例如,您可以将 testString() 实现为:

 int testString(char *output, int outputSize)
{
std::string const & s = getString();
if ( s.size() <= outputSize )
{
std::strncpy(output, s.c_str(), s.size());
return s.size(); //return the actual size of output
}
else //means s.size() > outputSize, i.e outputSize is smaller than required!
{
std::strncpy(output, s.c_str(), outputSize);
return s.size(); //return what is required (the actual size of output)!
}
}

然后在 C# 代码中,这样做:

[DllImport("MyDLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int testString(out StringBuilder output, int outputSize);

并将其命名为:

private static string ReturnSomething()
{
int bufferSize = 100;
StringBuilder buffer= new StringBuilder(bufferSize);
int outputSize = TestImport.testString(buffer, bufferSize);
if ( outputSize < bufferSize ) //output bufferSize was sufficient
{
return buffer.ToString();
}
else //output bufferSize was insufficient
{
//retry!
bufferSize = outputSize;
buffer = new StringBuilder(bufferSize); //reallocate!
outputSize = TestImport.testString(buffer, bufferSize);
if ( outputSize <= bufferSize )
return buffer.ToString();
else
{
throw new Exception("PANIC");
}
}
}

关于c# - 将 C++ 字符返回到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9356385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com