[英]Passing a string from a DLL to C#
我有一個C#應用程序,它使用CLI DLL從非托管C ++庫中訪問函數。 我的問題是我無法將C ++庫中的文本正確傳遞給C#應用程序。 我到目前為止的代碼如下:
C#
[DllImport("Wrapper.dll", EntryPoint = "GetNameLength", CallingConvention = CallingConvention = CallingConvention.Cdecl)]
public static extern bool _GetNameLength( int index, out int size);
[DllImport("Wrapper.dll", CharSet = CharSet.Ansi, EntryPoint = "GetName", CallingConvention = CallingConvention.Cdecl)]
public static extern bool _GetName( out Stringbuilder name, int size, int index);
private void TestFunction()
{
int size = 0;
_GetNameLength(2, out size);
StringBuilder str = new StringBuilder(size + 1);
_GetName(out str, str.Capacity, 2);
btnName.Text = str.ToString();
}
CLI
// In the header.
#define DllExport __declspec( dllexport)
extern "C" {
DllExport bool __cdecl GetNameLength( int index, int& size);
DllExport bool __cdecl GetName( char* name, int size, int index);
};
// In the '.cpp'.
bool __cdecl GetNameLength( int index, int& size) {
if( gp_app == nullptr)
return false;
gp_app->GetNameLength( index, size);
return true;
}
bool __cdecl GetName( char* name, int index, int size) {
if( gp_app == nullptr)
return false;
const char* n = "";
n = gp_app->GetName( index);
name = new char[size];
strcpy( name, n);
return true;
}
C ++
// In the header.
class App {
void GetNameLength( int index, int& size);
const char* GetName( int index);
};
// In the '.cpp'.
void App::GetNameLength( int index, int& size) {
if( index >= 0 && index < gs_namesCount)
size = strlen( gs_names[index]);
}
const char* App::GetName( int index) {
if( index >= 0 && index < gs_namesCount)
return gs_names[index];
return nullptr;
}
我能夠調試DLL並且我已經看到它確實正確地復制了名稱,即使我只使用name = const_cast<char*>( n)
(當我使用字符串而不是StringBuilder時),但由於某種原因,該值不會從DLL返回到C#。
我讀到一個可能的原因是因為C ++可能使用ASCII字符,而C#使用16位字符,並且修復它是為了包括CharSet = CharSet.Ansi
以便它在返回C#時正確編組,但顯然沒有沒有幫助。
誰能告訴我我做錯了什么?
方案 :
使用public ref class
而不是命名空間,並使用void Foo( [Out] String^ %name)
聲明函數,確保using namespace System::Runtime::InteropServices;
已經包括了。
這告訴我你實際上有一個托管的c ++ dll。
if( gp_app == nullptr)
return false;
如果是這樣,您可以導出托管類並使用String作為方法的參數。
請檢查: http : //msdn.microsoft.com/library/windows/apps/hh699870.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.