473,541 Members | 14,799 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 13720
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
5311
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 tried several of the *.i libraries at http://www.swig.org/Doc1.3/Library.html. Most notably the "std_string.i" And get the following: >>>...
5
9385
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. If i make another constructor with parameter const char*, how can i call the constructor with the const string& ? I tried
10
14460
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 the "right" (i.e.wysiwyg) answer while compare() does not.
2
4799
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 std; int main()
5
8792
by: Jae | last post by:
Real(const string &fileName) { FILE * myInputFile = fopen(fileName, "rt"); ..... fclose(myInputFile);
2
10843
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 think for a sec. At first I read it as converting a 'const char *' to a 'std::string *' void f(const std::string &s) { std::cout << s.size() <<...
3
1779
by: sernamar | last post by:
Hi, I have the following base class class UnitOfMeasure { public: //... std::string& GetName() {return _uomName;}; //... protected:
1
1968
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, boost::python::return_value_policy<boost::python::copy_const_reference>() ); Is there a way to register a return value conversion for "const std::string&" so I can omit it every time I...
2
3430
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 stack and the parameter will refer to this object. Is this correct? Does this mean if a constructor of a class has a string reference parameter, the...
0
7372
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7711
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7657
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5845
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5231
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3366
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
937
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
605
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.