Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried different things but i'm getting mad with Interop.

(here the word string is not referred to a variabile type but "a collection of char"): I have an unmanaged C++ function, defined in a dll, that i'm trying to access from C#, this function has a string parameter and a string return value like this:

string myFunction(string inputString)
{
}

What should be string in C++ side? and C# one? and what parameters need DllImport for this?

like image 768
Smjert Avatar asked Feb 01 '10 18:02

Smjert


People also ask

What is pass in C?

Arguments in C and C++ language are copied to the program stack at run time, where they are read by the function. These arguments can either be values in their own right, or they can be pointers to areas of memory that contain the data being passed. Passing a pointer is also known as passing a value by reference.

Is there pass statement in C++?

No, C/C++, like most languages, has free form code and nested code blocks are surrounded by curly braces {…} . The pass keyword exists because Python has indented whitespace to mark nested code blocks. Here are several programming languages and their for-loop nested code blocks.

What is pass keyword in Python?

The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.


1 Answers

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 );
like image 127
Scott Saad Avatar answered Oct 01 '22 03:10

Scott Saad