On Mon, 4 Sep 2006 21:22:52 +0100, Jason wrote:
> Hi,
>
> I have a problem with some C# code. I have a function in a c++ dll which
> returns a BSTR. I have retrieved the BSTR using p/invoke but the data
> returned contains what appears to be random data at the start of the string
> followed by correct data. I am wondering whether it is the length of the
> BSTR prepended to the string that I am picking up, but doesn't
> SysAllocStringByteLen get rid of this?
>
> to retrieve the data:
>
> [DllImport("Test")]
> private static extern IntPtr getbagstr();
>
> public static string getBagString()
> {
> IntPtr ptr = getbagstr();
> string tmp = Marshal.PtrToStringAnsi(ptr);
> Marshal.FreeBSTR(ptr);
> return tmp;
> }
>
> This code appears to work when I alter the code within getbagstr() to
> return "dfksdjfkjd"; for example, but fails to return the extra data when
> returning an stl::string
>
> extern "C" __declspec( dllexport ) BSTR getbagstr();
> extern "C" __declspec( dllexport ) BSTR getbagstr() {
> const char * buff = g.getbag()->getbagstr(true).c_str();
> return SysAllocStringByteLen (buff , lstrlen(buff));
> }
>
>
> If I set the data from my C# class, see below, the string returned from the
> code above is a few bytes of junk as if i only have a pointer.
>
> private static extern void setbag(IntPtr ptr);
>
> public static void setdata(string str)
> {
> IntPtr ptr = Marshal.StringToBSTR(str);
>----- setbag(ptr.ToPointer());
> Marshal.FreeBSTR(ptr);
> }
>
> The corresponding setbag function accepts LPSTR, so I guess passing an
> IntPtr from a BSTR is the wrong way to go, but I am not sure anymore.
> Please someone help!
Sorry, did not call ToPointer(), should really be
setbag(ptr);
|