Click to See Complete Forum and Search --> : cannot convert char* to object or string?


cristi_alonso
May 23rd, 2008, 12:54 PM
i have created DLL in C which i am going to use in my C# code .
DLL file is TestLib.DLL
C# file is Test_Net.cs

-----------------TestLib.dll ------------------------------------
#include <stdio.h>

extern "C"
{
__declspec(dllexport) char* DisplayHelloFromDLL()
{
char* x="bach ke kaha jaoge";
return x;
}
}
-------------------End of file TestLib---------------------------------

-------------------------Test_Net.cs------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;

namespace Test_Net
{
public partial class Form1 : Form
{
[DllImport("TestLib.dll")]

public static unsafe extern char* DisplayHelloFromDLL();


public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{


}

private void button1_Click(object sender, EventArgs e)
{
unsafe
{

char* y = DisplayHelloFromDLL();
label2.Text = Convert.ToString(y);
}


}
}
}
-----------------------------EOF Test_Net-----------------------

While Debuging i am getting an error saying that cannot convert from char* to object .can anyone tell me how to solve this problem?please anyone can tell me how to convert char* to string or char* to char it will be very usefull .


Any help appreciated
Thanks in advance.

darwen
May 23rd, 2008, 03:14 PM
You can use System.Runtime.InteropServices.Marshal.PtrToStringAnsi if your char * is null terminated (i.e. it has a 0 as the last character).

Have a look at this sample code :


byte [] myByte = new byte[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)'\0' };

string result = string.Empty;

unsafe
{
fixed (byte* xx = &(myByte[0]))
{
result = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(new IntPtr(xx));
}
}

Console.WriteLine(result);


On a different note, a few points on style

(1) I hope you're not 'new'ing the memory for the char * and then returning it. C# has no way of releasing this memory. Returning a pointer to a variable which is released inside your dll is fine.

i.e.


// in dll

// bad ! Don't do anything like this !
char * getNameBad
{
char *xx = new char[3];
xx[0] = 'h';
xx[1] = 'e';
xx[2] = '\0';

return xx;
}

// better
std::string myName = "hello";

const char *getNameGood()
{
return myName.c_str();
}


(2) Don't put the interface code in the UI. You should have a separate class to do this. It should have a method which calls your dll method and returns a .NET string.

Darwen.