Reputation: 3742
I googled a lot & nothing is working in my case. Here is my code.
.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# (import)
[DllImport("Serializer", CharSet = CharSet.Ansi)]
private extern static void ToString_Internal(IntPtr a_ptr, StringBuilder a_builder);
C# (usage)
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
Question #1: Console.WriteLine() prints only first letter("t") in terminal. What is this issue?
Question #2: 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#).
If you guyz need more info, let me know.
Upvotes: 1
Views: 130
Reputation: 612834
Console.WriteLine()
prints only first letter("t") in terminal. What is this issue?
You only copied one character here:
*a_str = *pp;
Instead you need to copy the entire string:
strcpy(a_str, pp);
Of course, you are simply asking for a buffer overrun error with this code. You need to also pass the length of buffer when you call the function, and arrange that you do not copy beyond the end of that buffer.
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#).
The memory passed down to the C++ code is managed by the p/invoke framework, and it ensures that it is allocated and deallocated correctly. You do not need to do anything more.
From the code you present, it seems that the function uses the __cdecl
calling convention. Add CallingConvention = CallingConvention.Cdecl
to your DllImport
attribute:
[DllImport("Serializer", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl)]
Upvotes: 3