473,326 Members | 2,182 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Best way to interop C# System.String with C++ std::string&

I have some C++ unmanaged code that takes std::string& arguments (as
reference), and fills them (possibly growing the string).

I want to call this code through PInvoke (DllImport), possibly using
wrapper layers in unmanaged C++ and C#.

I've thought about two approaches:

1) To pass a StringBuilder, this is converted to a char* in C++, the
wrapper code converts the char* to a std::string (copy), and in the
end, copies the std::string content back to the char*. The problem is
that the StringBuilder cannot grow in C++ code (or maybe it can? with
callbacks?), it must be initialized in C# with a size that is not
known beforehand; this also seems insecure.

2) To pass a "ref String", this is converted to a "char** arg". The
wrapper code converts *arg to a string, and in the end, should set
*arg to a new value. I don't know if the *arg pointer can really be
changed... if I create a new char[] block in the C++ heap and pass it
back (setting it to *arg), it results in a heap error (although the
string returned is correct).

All of these approaches involves copying the data (sometimes more than
twice), but, by now, I just want to make it work. Are there better
ways to accomplish this?

Thanks,
Edson
Jun 27 '08 #1
8 13675
On May 6, 4:52*am, Edson Manoel <e.ta...@gmail.comwrote:
I have some C++ unmanaged code that takes std::string& arguments (as
reference), and fills them (possibly growing the string).

I want to call this code through PInvoke (DllImport), possibly using
wrapper layers in unmanaged C++ and C#.

I've thought about two approaches:

1) To pass a StringBuilder, this is converted to a char* in C++, the
wrapper code converts the char* to a std::string (copy), and in the
end, copies the std::string content back to the char*. The problem is
that the StringBuilder cannot grow in C++ code (or maybe it can? with
callbacks?), it must be initialized in C# with a size that is not
known beforehand; this also seems insecure.

2) To pass a "ref String", this is converted to a "char** arg". The
wrapper code converts *arg to a string, and in the end, should set
*arg to a new value. I don't know if the *arg pointer can really be
changed... if I create a new char[] block in the C++ heap and pass it
back (setting it to *arg), it results in a heap error (although the
string returned is correct).

All of these approaches involves copying the data (sometimes more than
twice), but, by now, I just want to make it work. Are there better
ways to accomplish this?

* Thanks,
Edson
Not sure if this would help, but here it is:

System::Void ManagedToBasicString(String^ iSourceStr,
std::string &oTargetStr)
{
oTargetStr = std::string((char*)
(void*)Marshal::StringToHGlobalAnsi(iSourceStr));
return;
}

Good luck:-)
Jun 27 '08 #2
On May 6, 4:52*am, Edson Manoel <e.ta...@gmail.comwrote:
I have some C++ unmanaged code that takes std::string& arguments (as
reference), and fills them (possibly growing the string).

I want to call this code through PInvoke (DllImport), possibly using
wrapper layers in unmanaged C++ and C#.

I've thought about two approaches:

1) To pass a StringBuilder, this is converted to a char* in C++, the
wrapper code converts the char* to a std::string (copy), and in the
end, copies the std::string content back to the char*. The problem is
that the StringBuilder cannot grow in C++ code (or maybe it can? with
callbacks?), it must be initialized in C# with a size that is not
known beforehand; this also seems insecure.

2) To pass a "ref String", this is converted to a "char** arg". The
wrapper code converts *arg to a string, and in the end, should set
*arg to a new value. I don't know if the *arg pointer can really be
changed... if I create a new char[] block in the C++ heap and pass it
back (setting it to *arg), it results in a heap error (although the
string returned is correct).

All of these approaches involves copying the data (sometimes more than
twice), but, by now, I just want to make it work. Are there better
ways to accomplish this?

* Thanks,
Edson
How about

- you write a mixed (managed/native) wrapper
- you pass a System::String by reference to the wrapper
- in the wrapper scope, you fetch the std::string from unmanaged code,
and assign to the referenced System::String?

I dont see why that wont work.
Jun 27 '08 #3
Edson... Is it possible that your code could take a managed string as an
in
parameter, convert the managed string to char*, call the C++ code, and
then
RETURN a new managed string on method exit? The following code was a
quick hack taking a std::string and returning a managed string. I
readily
admit I only dabble in STL/CLI.

using namespace System;
using namespace cliext; // STL/CLR
using namespace System::Runtime::InteropServices; // Marshal

class Util {
public:
/////////////////////////////////////////////////////////
// ** ConvertSS2MS ** //
// Converts std::string to managed String^ //
// Parameters constant std::string in by ref //
// Returns String^ out //
// Static Public Class method //
// Internally converts to most common denominator //
// char* on heap using new and delete //
// std::string ref in cannot be null, but may be empty //
// Returns empty string on exception //
// JAL 12/04/08 //
/////////////////////////////////////////////////////////

static String^ ConvertSS2MS(const std::string& in) {
String^ out= L""; // L wchar_t typedef unsigned short
char* str=0;
size_t size= strlen(in.c_str()) +1; // +1 for null terminator

try {
//const char *p= in.c_str(); // use p immediately
//out= Marshal::PtrToStringAnsi(static_cast<IntPtr>(p)); //
error on const char *
str= new char[size]; // null terminated
strcpy_s(str,size,in.c_str()); // create longer lived copy in
non const char array
// strcpy_s has new security enhancements over strcpy,
size includes null char
out= Marshal::PtrToStringAnsi(static_cast<IntPtr>(str)) ; //
or safe_cast?
}
catch(...) { // eat the exception
out= L""; // returns empty string on exception
}
finally { // clean up memory
if(str) {
delete [] str; // release char[] on unmanaged heap,
delete [] calls destructors
}
}
return out;
} // end ConvertSS2MS
}; // end class Util

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Jun 27 '08 #4
On Tue, 6 May 2008 04:52:30 -0700 (PDT), Edson Manoel
<e.*****@gmail.comwrote:
>All of these approaches involves copying the data (sometimes more than
twice), but, by now, I just want to make it work. Are there better
ways to accomplish this?
You always will have to copy the data because .NET strings are
internally encoded in Unicode UTF-16 which uses two bytes per
character, whereas C++ std::string uses an implementation-specific
ASCII superset with one byte per character. So there's no way to just
share a common buffer if you were thinking of that.
--
http://www.kynosarges.de
Jun 27 '08 #5
On May 7, 3:40 am, Chris Nahr <dioge...@kynosarges.dewrote:
On Tue, 6 May 2008 04:52:30 -0700 (PDT), Edson Manoel

<e.ta...@gmail.comwrote:
All of these approaches involves copying the data (sometimes more than
twice), but, by now, I just want to make it work. Are there better
ways to accomplish this?

You always will have to copy the data because .NET strings are
internally encoded in Unicode UTF-16 which uses two bytes per
character, whereas C++ std::string uses an implementation-specific
ASCII superset with one byte per character. So there's no way to just
share a common buffer if you were thinking of that.
--http://www.kynosarges.de
Thanks for all the answers!

I solved it passing a ref string; this is marshaled to a char**.
Dereferencing it in C++, I get a char*, then I build a std::string
from it and pass it to my C++ method. After the call to the method, I
use CoTaskMemFree to free the original char*, and then I allocate a
new char* buffer with CoTaskMemAlloc, with the returned std::string
size().

So, in the end, to just pass one string and get it returned, there are
at least 4 copies being made (C# string to char* conversion; char* to
std::string / input and output), 3 allocations (char*, std::string and
my own CoTaskMemAlloc) and 3 deallocations. Well, at least, It Just
Works® :p. I wish that it were faster, but it seems that C# (and CLR
in general) weren't made to speak with *unmanaged* C++ code... (only
C).

I guess this does not leak memory, am I right?

I've learned that .Net uses CoTaskMemAlloc/CoTaskMemFree through some
websites (Msdn, etc.). I couldn't debug inside the Microsoft code that
does the marshaling (/interop)... is there any way to do this, or am I
not allowed to see the magic trickery that is going on besides the
curtain?

Thanks,
Edson
Jun 27 '08 #6
So, in the end, to just pass one string and get it returned, there are
at least 4 copies being made (C# string to char* conversion; char* to
std::string / input and output), 3 allocations (char*, std::string and
my own CoTaskMemAlloc) and 3 deallocations. Well, at least, It Just
Works® :p. I wish that it were faster, but it seems that C# (and CLR
in general) weren't made to speak with *unmanaged* C++ code... (only
C).
Well, this is only partly true. There is no support in the CLR for C++
interop other than what is needed to make the C++/CLI compiler work. You
are expected to use C++/CLI for tasks like this.

Here is how you would avoid the extra copies (still need Unicode conversion
of course):

void LetsNativeCodeOperateOnManagedString(System::Strin g^% managedString)
{
int len = managedString->Length;
std::string nativeString;
nativeString.reserve(len + 1);
WideCharToMultiByte(..., PtrToStringChars(managedString), len,
&(nativeString[0]), len, ...);

callNativeFunction(nativeString);

managedString = gcnew String^(nativeString, nativeString.length());
}
Jun 27 '08 #7
Ben Voigt [C++ MVP] wrote:
>So, in the end, to just pass one string and get it returned, there
are at least 4 copies being made (C# string to char* conversion;
char* to std::string / input and output), 3 allocations (char*,
std::string and my own CoTaskMemAlloc) and 3 deallocations. Well, at
least, It Just Works® :p. I wish that it were faster, but it seems
that C# (and CLR in general) weren't made to speak with *unmanaged*
C++ code... (only C).

Well, this is only partly true. There is no support in the CLR for
C++ interop other than what is needed to make the C++/CLI compiler
work. You are expected to use C++/CLI for tasks like this.

Here is how you would avoid the extra copies (still need Unicode
conversion of course):

void LetsNativeCodeOperateOnManagedString(System::Strin g^%
managedString) {
int len = managedString->Length;
std::string nativeString;
nativeString.reserve(len + 1);
WideCharToMultiByte(..., PtrToStringChars(managedString), len,
&(nativeString[0]), len, ...);

callNativeFunction(nativeString);

managedString = gcnew String^(nativeString, nativeString.length());
oops, should be gcnew String, not gcnew String^
}

Jun 27 '08 #8
Ben Voigt [C++ MVP] wrote:
>So, in the end, to just pass one string and get it returned, there
are at least 4 copies being made (C# string to char* conversion;
char* to std::string / input and output), 3 allocations (char*,
std::string and my own CoTaskMemAlloc) and 3 deallocations. Well, at
least, It Just Works® :p. I wish that it were faster, but it seems
that C# (and CLR in general) weren't made to speak with *unmanaged*
C++ code... (only C).

Well, this is only partly true. There is no support in the CLR for
C++ interop other than what is needed to make the C++/CLI compiler
work. You are expected to use C++/CLI for tasks like this.

Here is how you would avoid the extra copies (still need Unicode
conversion of course):
Of course 2008 gives you all of this in the Microsoft-provided marshal_as
function.
>
void LetsNativeCodeOperateOnManagedString(System::Strin g^%
managedString) {
int len = managedString->Length;
std::string nativeString;
nativeString.reserve(len + 1);
WideCharToMultiByte(..., PtrToStringChars(managedString), len,
&(nativeString[0]), len, ...);

callNativeFunction(nativeString);

managedString = gcnew String^(nativeString, nativeString.length());
}

Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Leonard J. Reder | last post by:
Hello, I have been trying to get this simple call to work with a SWIG interface. The problem is I do not know how to pass a const char * or a std::string & in python to SWIG wrapped code. I...
5
by: selder21 | last post by:
Hello, I have a class with constructor taking a const string&. Now i want to call this constructor with a string literal. Because this is of type char* there are overload resolution conflicts....
10
by: lchian | last post by:
Hi, For two stl strings s1 and s2, I got different results from strcmp(s1.c_str(), s2.c_str()) and s1.compare(s2) can someone explain what these functions do? It seems that strcmp gives...
2
by: zhege | last post by:
I am a beginner of C++; I have a question about the std:string and std:cout class; Two pieces of code: -------------------------------- #include <iostream> #include <string> using namespace...
5
by: Jae | last post by:
Real(const string &fileName) { FILE * myInputFile = fopen(fileName, "rt"); ..... fclose(myInputFile);
2
by: pookiebearbottom | last post by:
Just looking for opinion on which of the 3 methods below people use in their code when they convert a 'const char *' to a 'const std::string &' came across #3 in someone's code and I had to...
3
by: sernamar | last post by:
Hi, I have the following base class class UnitOfMeasure { public: //... std::string& GetName() {return _uomName;}; //... protected:
1
by: gabriel.becedillas | last post by:
I have a lot of functions returning "const std::string&". Every time I wrap one of those I have to do it like this: class_.def("name", &someclass::bla,...
2
by: ragged_hippy | last post by:
Hi, If I have a method that has string reference as a parameter, what happens if I pass a const char* variable to this method? One thought is that a temporary string will be created in the...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.