将字符串从 C++ 传递到 C# 不起作用
Passing string from C++ to C# not working
我在谷歌上搜索了很多,但我的情况没有任何效果。这是我的代码。
.cpp
char* pp = "this_is_text";
DLL_EXPORT void ToString_Internal(MicroObject* a_microObj, char* a_str)
{
*a_str = *pp;
}
#define DLL_EXPORT __declspec(dllexport)
C#(导入)
[DllImport("Serializer", CharSet = CharSet.Ansi)]
private extern static void ToString_Internal(IntPtr a_ptr, StringBuilder a_builder);
C#(用法)
StringBuilder l_builder = new StringBuilder(1000); //set 1000 len, for testing
ToString_Internal (m_ptr, l_builder); //invoke to DLL function
Console.WriteLine (l_builder.ToString ()); //print to console
问题 #1:Console.WriteLine() 在终端中仅打印第一个字母 ("t")。这是什么问题?
问题 #2:我在 C# 中分配内存(使用 StringBuilder)。在我的情况下,C# GC 是释放内存还是我必须手动释放内存以及在哪一侧(C 或 C#)。
如果你们需要更多信息,请告诉我。
Console.WriteLine()
prints only first letter("t") in terminal. What is this issue?
您在这里只复制了一个字符:
*a_str = *pp;
相反,您需要复制整个字符串:
strcpy(a_str, pp);
当然,您只是在请求此代码的缓冲区溢出错误。您还需要在调用该函数时传递缓冲区的长度,并安排您不要复制超出该缓冲区的末尾。
I am allocating memory in C#(using StringBuilder). Is C# GC deallocating memory in my case or do i have to deallocate memory manually and in which side(C or C#).
传递给 C++ 代码的内存由 p/invoke 框架管理,它确保它被正确分配和释放。您无需再做任何事情。
从您提供的代码来看,该函数似乎使用了 __cdecl
调用约定。将 CallingConvention = CallingConvention.Cdecl
添加到您的 DllImport
属性:
[DllImport("Serializer", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl)]
我在谷歌上搜索了很多,但我的情况没有任何效果。这是我的代码。
.cpp
char* pp = "this_is_text";
DLL_EXPORT void ToString_Internal(MicroObject* a_microObj, char* a_str)
{
*a_str = *pp;
}
#define DLL_EXPORT __declspec(dllexport)
C#(导入)
[DllImport("Serializer", CharSet = CharSet.Ansi)]
private extern static void ToString_Internal(IntPtr a_ptr, StringBuilder a_builder);
C#(用法)
StringBuilder l_builder = new StringBuilder(1000); //set 1000 len, for testing
ToString_Internal (m_ptr, l_builder); //invoke to DLL function
Console.WriteLine (l_builder.ToString ()); //print to console
问题 #1:Console.WriteLine() 在终端中仅打印第一个字母 ("t")。这是什么问题?
问题 #2:我在 C# 中分配内存(使用 StringBuilder)。在我的情况下,C# GC 是释放内存还是我必须手动释放内存以及在哪一侧(C 或 C#)。
如果你们需要更多信息,请告诉我。
Console.WriteLine()
prints only first letter("t") in terminal. What is this issue?
您在这里只复制了一个字符:
*a_str = *pp;
相反,您需要复制整个字符串:
strcpy(a_str, pp);
当然,您只是在请求此代码的缓冲区溢出错误。您还需要在调用该函数时传递缓冲区的长度,并安排您不要复制超出该缓冲区的末尾。
I am allocating memory in C#(using StringBuilder). Is C# GC deallocating memory in my case or do i have to deallocate memory manually and in which side(C or C#).
传递给 C++ 代码的内存由 p/invoke 框架管理,它确保它被正确分配和释放。您无需再做任何事情。
从您提供的代码来看,该函数似乎使用了 __cdecl
调用约定。将 CallingConvention = CallingConvention.Cdecl
添加到您的 DllImport
属性:
[DllImport("Serializer", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl)]