Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there any way to create a function that returns a char array from c++ dll to a char array or string in c#?
Posted
Comments
Toli Cuturicu 6-Sep-10 12:27pm    
Yes. Where exactly is your problem. Show us what you tried so far.
Sandeep Mewara 6-Sep-10 13:19pm    
Heard of managed-unmanaged code?
DaveyM69 9-Sep-10 3:25am    
The answer is - it depends! Is the C++ function actually returning a char[] or a pointer to one? Where is the length of the array specified - in a parameter or a constant, or is it a null terminated one in which case it's really a string?
The easiest way for us to help you is if you give us the original C++ function declaration, from there it's normally pretty easy.
Alternatively, check out http://msdn.microsoft.com/en-us/magazine/cc164123.aspx, especially the 'Marshaling Text' section.

In your C++ DLL:
C
__declspec(dllexport) TCHAR* __cdecl testString();

__declspec(dllexport) TCHAR* testString()
{
    return _T("Wheee!");
}


And to call it from your C# you need to do something like:
C#
class Program
{
[DllImport("MyDLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr testString();

void CallCppDLL()
{
IntPtr t = testString();
String result = Marshal.PtrToStringAuto(t);
}
}


I haven't done this in quite some time, so feel free to correct me :)
 
Share this answer
 
It doesn't work because the returning address is of a local variable...
any other ideas?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900