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

前端 未结 4 2009
灰色年华
灰色年华 2021-02-09 16:37

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-09 16:58

    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.

提交回复
热议问题