I would appreciate if someone could provide some information on passing string value from a unmanaged C++ code to a equuivalent managed string object? .
When passed as a Func(const char * s) from unmanaged c++ code and try to access the Func from c# ,the signature changes to Func(sbyte*) .
PrashantPosted Jul 15, 2008, 3:45 AM
Hello Alan ,
Thanks a lot for your reply .
Not exactly what i wanted . I have a unmanaged C++ class and i am creating a wrapper class for it , where one of my function takes a parameter as (const char *s) ex :-
func(const char *s){ } . The wrapper what i have created is a dll application and when i import the dll into my c# application the signature changes to
func (sbyte*), whereas i need something like func(string) in my c# application...Hope it clarifies the problem .
AlanPosted Jul 8, 2008, 3:59 PM
If I've understood that correctly, it looks like you're going to have to convert a managed string to an sbyte* before you can call the unmanaged function from C#. This short program illustrates the principle:
using System;
unsafe class Program
{
static void Main()
{
string s = "Hello"; // needs to be plain ascii chars 0 - 127
sbyte[] sba = new sbyte[s.Length + 1]; // including final null byte
for(int i = 0; i < s.Length; i++)
{
sba[i] = (sbyte)s[i];
}
fixed(sbyte* sbp = sba)
{
Func(sbp);
}
Console.WriteLine();
Console.ReadLine();
}
static void Func(sbyte* sbp)
{
int count = 0;
while(sbp[count] != 0) Console.Write((char)sbp[count++]);
}
}