Search code examples
c#c++windows-ce

Return string from c++ dll export function called from c#


I am trying to return a string from a c++ dll export function. I am calling this function from c#. I have seen a lot of examples on the internet and I am really confused what to do.

My c++ code to export function:

extern "C" __declspec(dllexport)  char*  __cdecl getDataFromTable(char* tableName)
{
    std::string st = getDataTableWise(statementObject, columnIndex);
    printf(st.c_str()); 

    char *cstr = new char[st.length() + 1];
    strcpy(cstr, st.c_str());
    return cstr;
} 

When I try to call this function from c#:

[DllImport("\\SD Card\\ISAPI1.dll")]
private static extern string getDataFromTable(byte[] tablename);
static void Main(string[] args)
{
    string str = getDataFromTable(byteArray);
    Console.writeLine(str);
}

I got an error while calling it. I am creating this for WinCE 6.0

EDITED------------------------

is there something like, i can pass a empty buffer to c++ from c# and c++ function will fill the data and i can reuse it in C#


Solution

  • How about this (Note, it assumes correct lengths - you should pass in the buffer length and prevent overflows, etc):

    extern "C" __declspec(dllexport)  void  __cdecl getDataFromTable(char* tableName, char* buf)
    {
        std::string st = getDataTableWise(statementObject, columnIndex);
        printf(st.c_str()); 
    
        strcpy(buf, st.c_str());
    } 
    

    Then in C#:

    [DllImport("\\SD Card\\ISAPI1.dll")]
    private static extern string getDataFromTable(byte[] tablename, byte[] buf);
    static void Main(string[] args)
    {
        byte[] buf = new byte[300];
        getDataFromTable(byteArray, buf);
        Console.writeLine(System.Text.Encoding.ASCII.GetString(buf));
    }
    

    Note, this does make some assumptions about character encodings in your C++ app being NOT unicode. If they are unicode, use UTF16 instead of ASCII.