The definition of the exported function in c++ DLL is
int func1(const char* input,char** output)
{
int returnCode = 0;
std::stringstream xmlInputStream;
xmlInputStream<< std::string(input);
std::stringstream xmlOutputStream;
returnCode = doRequest(xmlInputStream,xmlOutputStream);
std::string xmlOutputString =xmlOutputStream.str();
*output=const_cast<char *> (xmlOutputString.c_str());
cout<<xmlOutputString;
return returnCode ;
}
I tried to import the function from c# like this…
==================================================================
[DllImport("sample.dll")]
public static extern int func1(String str1,out String str2);
string str1="hello";
string str2=String.Empty;
MyClass.func1(str1,out str2);
Console.writeln(str2);
====================================================================
Output is garbage value…
Why is it so and how to import this function from c#?
Thats simple, try to use custom marshaling (especially if you want to use char** pointers).
I found that you are no getting “Memory ass dumb” string, because of some improper realization of doRequest(char*,char**), as well as assigning to the result is not properly handled;
Firstly, if you are allocating memory in unmanaged process and passes it to managed process, you will need declare some mechanism to free unmanaged memory. Managed GC does not know anything about this memory, which will be lost overwize.
Secondy, you need to allocate memory for the results, and pass them to the unmanaged process, because the original memory locations can be rewritten in any time.
Lastly, you are getting only the first characted of the input just because you are not allocated memory for the results, effectively passing only a memory pointer to the memory location of the first output character, say &array[0]
Here is the compete code (MS VC++/MS C#), which fixes all the issues:
lib.cpp:
Program.cs: