2011-04-30 123 views
1

如何使用字符串參數從C#WPF應用程序調用C++ dll中的函數?我通過「添加引用」添加DLL到C#應用程序,而不是「[DLLImport]」將字符串傳遞給dll

所有問題是,C#建議函數與'sbyte *'參數,而不是'char *'。 'int'參數的函數是完美的。

這裏是代碼:

我在c函數++ DLL:

public ref class OpenGLHwnd : public HwndHost 
{ 
public: 
    void myFunc(char* name) 
    { 
     // some code 
    } 

C#代碼:

HwndHost host = new WPFOpenGLLib.OpenGLHwnd(); 
HWNDPlaceholder.Child = host; 
(HWNDPlaceholder.Child as WPFOpenGLLib.OpenGLHwnd).myFunc("aaaa"); 

myFunc的希望 '爲sbyte *' parametr,而不是 '字符*'。爲什麼?

或者告訴請,如何將字符串轉換到sbyte *

回答

3

因爲你的C++ DLL顯然是一個.NET程序集(ref class,即C++/CLI),你可以把這個字符串作爲.NET String

#include <msclr/marshal.h> 
using namespace msclr::interop; 

public ref class OpenGLHwnd : public HwndHost 
{ 
public: 
    void myFunc(System::String^ name) 
    { 
     marshal_context^ context = gcnew marshal_context(); 
     const char* ptr = context->marshal_as<const char*>(name); 
     puts(ptr); 
     delete context; 
    }