Pass C# String to C++ and Pass C++ Result (String, Char*.. Whatever) to C#

Pass C# string to C++ and pass C++ result (string, char*.. whatever) to C#

What I've found to work best is to be more explicit about what's going on here. Having a string as return type is probably not recommended in this situation.

A common approach is to have the C++ side be passed the buffer and buffer size. If it's not big enough for what GetString has to put in it, the bufferSize variable is modified to indicate what an appropriate size would be. The calling program (C#) would then increase the size of the buffer to the appropriate size.

If this is your exported dll function (C++):

extern "C" __declspec void GetString( char* buffer, int* bufferSize );

Matching C# would be the following:

void GetString( StringBuilder buffer, ref int bufferSize );

So to use this in C# you would then do something like the following:

int bufferSize = 512;
StringBuilder buffer = new StringBuilder( bufferSize );
GetString( buffer, ref bufferSize );

pass char * to C DLL from C# string

Update your P/Invoke declaration of your external function as such:

[DllImport("dork.dll")]
public static extern int CopyFunc([MarshalAs( UnmanagedType.LPStr )]string a, [MarshalAs( UnmanagedType.LPStr )] string b);

int GetFuncVal(string src, string dest)
{
return(CopyFunc(dest,src));
}

passing char pointer array of c++ dLL to c# string

we can do it as

in DLL we will have

    extern "C" __declspec(dllexport) void  __stdcall Caller() 
{

static char* myArray[3];

myArray[0]="aasdasdasdasdas8888";

myArray[1]="sssss";

FunctionPtr1(2,myArray);

}

and in C# i just added following lines

public static void ping(int a, IntPtr x)
{

Console.WriteLine("Entered Ping Command");
//code to fetch char pointer array from DLL starts here
IntPtr c = x;
int j = 0;
string[] s = new string[100]; //I want this to be dynamic
Console.WriteLine("content of array");
Console.WriteLine("");

do
{
s[j] = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(c, 4 * j));
Console.WriteLine(s[j]);
j++;

} while (s[j - 1] != null);
//**********end****************

Console.WriteLine("Integer value received from DLL is "+a);

}

passed strings from C# is different with C++ strings , both are const char

You can't compare strings like that :

if (string_from_csharp == "hello world!" )

If you absolutely need to use char*, use strcmp, or strncmp.

extern "C" __declspec(dllexport) int check_string(const char* string_from_csharp);
bool check_string(const char* string_from_csharp)
{
return (strcmp(string_from_csharp, "hello world!") == 0);
}

You may want to use std::string since you're in C++. In that case, you'd use std::string::compare.



Related Topics



Leave a reply



Submit