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

前端 未结 4 2013
灰色年华
灰色年华 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 17:22

    On windows you can return string directly using BSTR (from wtypes.hincluded by windows.h). BSTRcan be created from standard wide string bySysAllocString function:

    _declspec(dllexport) BSTR getDataFromTable(const char* tableName)
    {
        return SysAllocString(L"String to return");
    }
    

    Then in C# you marshal the return type as BStr:

    [DllImport("\\SD Card\\ISAPI1.dll", CallingConvention = CallingConvention.Cdecl )]
    [return: MarshalAs(UnmanagedType.BStr)]
    static extern string getDataFromTable(string tableName);
    

提交回复
热议问题