473,721 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Marshal::String ToXXX question

Hi all!

I need to pass managed String from to C-style APIs. I see I can use
Marshal::String ToXXX functions. Is this the best we have? I understand
this will allocate a new string and create copy of my String. I want to
pass it as constant (LPCWSTR). I don't need allocation and copying,
just the pointer. Can I have it, pretty please?

In normal C++, we usually have conversion operator or a function to get
it from a string class (string::c_str( ) or CString::operat or LPCTSTR or
_bstr_t::operat or LPCTSTR etc). Is there a similar thing in .NET?

Thanks, Goran.

Aug 31 '06 #1
1 1313
Hi Goran!
I need to pass managed String from to C-style APIs. I see I can use
Marshal::String ToXXX functions. Is this the best we have? I understand
this will allocate a new string and create copy of my String. I want to
pass it as constant (LPCWSTR). I don't need allocation and copying,
just the pointer. Can I have it, pretty please?
If you just need an unciode-string, you can use (version for VC2003):

#include <vcclr.h>

const __wchar_t __pin * unmanaged_str = PtrToStringChar s(managed_str);

And use the "unmanaged_ str" pointer.
See also:
http://blog.kalmbachnet.de/?postid=18
http://support.microsoft.com/kb/311259/
In normal C++, we usually have conversion operator or a function to get
it from a string class (string::c_str( ) or CString::operat or LPCTSTR or
_bstr_t::operat or LPCTSTR etc). Is there a similar thing in .NET?
For conversion you could use the following (version for VC2005):

#include <windows.h>
#include <tchar.h>
#include <string>
using namespace System;
struct StringConvA
{
char *szAnsi;
StringConvA(Sys tem::String ^s)
:
szAnsi(static_c ast<char*>(Syst em::Runtime::In teropServices:: Marshal::String ToHGlobalAnsi(s ).ToPointer()))

{}
~StringConvA()
{

System::Runtime ::InteropServic es::Marshal::Fr eeHGlobal(IntPt r(szAnsi));
}
operator LPCSTR() const
{
return szAnsi;
}
};

struct StringConvW
{
wchar_t *szUnicode;
StringConvW(Sys tem::String^ s)
:
szUnicode(stati c_cast<wchar_t* >(System::Runti me::InteropServ ices::Marshal:: StringToHGlobal Uni(s).ToPointe r()))

{}
~StringConvW()
{

System::Runtime ::InteropServic es::Marshal::Fr eeHGlobal(IntPt r(szUnicode));
}
operator LPCWSTR() const
{
return szUnicode;
}
};

#ifdef _UNICODE
#define StringConvT StringConvW
#else
#define StringConvT StringConvA
#endif

int _tmain()
{
String ^s = "abc";
std::string ansi = StringConvA(s);
std::wstring unicode = StringConvW(s);
_tprintf(_T("%s "), (LPCTSTR) StringConvT(s)) ;
}

Greetings
Jochen
Aug 31 '06 #2

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

Similar topics

5
2519
by: Carlos Guzmán Álvarez | last post by:
Hello: I'm trying to execute a function of a unmanaged dll using PInvoke, i have definied the function as: public static extern int isc_dsql_prepare( int status_vector, ref int trans_handle, ref int stmt_handle,
7
5530
by: Kevin | last post by:
Hi al I have an interesting question.... I am working witha Win API this is the Function Public Declare Function EnumJobs Lib "winspool.drv" Alias "EnumJobsA" (ByVal hPrinter As Long, ByVal FirstJob As Long, ByVal NoJobs As Long, ByVal Level As Long, pJob As Byte, ByVal cdBuf As Long, pcbNeeded As Long, pcReturned As Long) As Lon Which I got from the API viewer that comes with VB 6. I have tried to convert it to the following ...
2
1661
by: chaor | last post by:
hi, how to convert the following strut into safe struct in c#? struct in C++: typedef struct { char m_username; char m_password; char m_userIP;
16
2498
by: Duncan Mole | last post by:
Hi, This is probably an easy one but it iy first bit of p/invoke. I am trying to use the following C struct in a call: typedef struct { BYTE SRB_Cmd; BYTE SRB_Status, BYTE SRB_HaId;
2
1958
by: Laurent | last post by:
Hi again, I created a thread some days ago, while I was trying to access a C++ DLL using my C# program. First of all, I want to thanks all the guys who helped me. But I still have a problem... My C++ DLL has a function which has the following prototype: long FF_Function(void* inInstance, char* inDate, FF_Struct**
6
2719
by: william.thorpe.b | last post by:
I have recently switched from VS2003 to VS2005 and at the same time from V1 to V2 of the .NET Compact Framework. The target is a Windows CE 5.0 device and an ARMV4I processor. System.Runtime.InteropServices.Marshal.WriteInt32 used to work fine but now is misbehaving. I wrote some native-code (C++) alternates to some Marshal methods and when I P/Invoke them they work fine; I can write to an address and I read back the same value that...
6
2070
by: Gunawan | last post by:
Dear All, I have create an excel (COM Object) using this code Excel.Application xls = new Excel.Application(); but I can not remove it from memory although I have using close and quit wb.Close(false, false, 0); xls.Quit();
11
3942
by: michelqa | last post by:
Hello, I can retrieve column text from a ListView in another process but I cant figure out how to access to structure elements (LVCOLUMN) <code> //Handle variable is a valid ListView handle LV_COLUMN ListViewItem = new LV_COLUMN(); IntPtr ListViewItemPointer = IntPtr.Zero;
0
2730
by: xrxst32 | last post by:
Hello there, I have some doubts about the best practice for using COM automation, the Runtime Callable Wrapper (RCW) and Marshal.ReleaseComObject. So the question is/are: Do I need to release each COM object explicit by a call to Marshal.ReleaseComObject, does the RCW take care of that or does it leaks unmanaged resources?
0
8840
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8730
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9367
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9215
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9064
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5981
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4484
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2130
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.