RE: Passing strings to C++ DLL
- From: KH <KH@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Wed, 2 Jul 2008 06:45:00 -0700
Andy, a couple options:
1) Look at the MarshalAsAttribute which tells .NET how to translate its
unicode string between it and unmanaged code; the attribute is applied to the
argument, here's the example from MSDN:
void MyMethod( [MarshalAs(LPStr)] string s);
2) The other option is to write the wrapper in managed C++; if you go this
route your method calls will look something like this:
void MyMethod(String^ s)
{
IntPtr ptr = Marshal::StringToHGlobalAnsi(str);;
try
{
SDCERR err = GetCurrentConfig( (char*)ptr.ToPointer() );
}
finally
{
if (ptr.ToPointer()) Marshal::FreeHGlobal(ptr);
}
}
HTH - KH
"Andy Baker" wrote:
I am attempting to write a .NET wrapper for a C++ DLL file, but am having.
problems with passing strings as parameters. How should I be writing my C#
function call when the C header file is definined as taking a char * as an
argument? For example the C++ header says
SDCERR GetCurrentConfig(DWORD *num, char *name);
I am using Uint for the *num parameter, which returns the correct value
but for *name, I always get back a string of 6 squares. I have tried using
string, StringBuilder and char arrays, and passing by ref and not, but
always get the same result.
Connected to this I am also having problems with passing structures for
C++ functions - the structures contain strings as well. Whenever I call a
function that requires a structure as a parameter, I always get a
NotSupportedException, does this just mean that I have defined my structure
incorrectly? Do I have to initailise the structure beforehand (have tried
this but still didn't work)?
I am using Visual Studio 2005, and if it makes a difference it is for a
Compact Framework device. Thanks in advance for any help.
Andy Baker
- Follow-Ups:
- Re: Passing strings to C++ DLL
- From: Andy Baker
- Re: Passing strings to C++ DLL
- References:
- Passing strings to C++ DLL
- From: Andy Baker
- Passing strings to C++ DLL
- Prev by Date: Re: Passing long Strings as parameters (by ref and by value)
- Next by Date: Re: What is "class coupling", please?
- Previous by thread: Re: Passing strings to C++ DLL
- Next by thread: Re: Passing strings to C++ DLL
- Index(es):
Relevant Pages
|