2012-11-22 120 views
1

我想從C#傳遞一個字符串到C++,使用平臺調用。Dllimport從C#傳遞字符串到C++

  • C++代碼:

    #include<string> 
    using namespace std; 
    
    extern "C" 
    { 
        double __declspec(dllexport) Add(double a, double b) 
        { 
         return a + b; 
        } 
        string __declspec(dllexport) ToUpper(string s) 
        { 
         string tmp = s; 
         for(string::iterator it = tmp.begin();it != tmp.end();it++) 
          (*it)-=32; 
         return tmp; 
        } 
    } 
    
  • C#代碼:

    [DllImport("TestDll.dll", CharSet = CharSet.Ansi, CallingConvention =CallingConvention.Cdecl)] 
    public static extern string ToUpper(string s); 
    
    static void Main(string[] args) 
    { 
        string s = "hello"; 
        Console.WriteLine(Add(a,b)); 
        Console.WriteLine(ToUpper(s)); 
    } 
    

我接收SEHException。是否不可能像這樣使用std::string?我應該用char*代替嗎?

回答

0

我建議使用char *。這裏可能的解決方案。

如果你創建另一個C#功能ToUpper_2如下

C#的一面:

[DllImport("TestDll.dll"), CallingConvention = CallingConvention.Cdecl] 
private static extern IntPtr ToUpper(string s); 

public static string ToUpper_2(string s) 
{ 
    return Marshal.PtrToStringAnsi(ToUpper(string s)); 
} 

C++方面:

#include <algorithm> 
#include <string> 

extern "C" __declspec(dllexport) const char* ToUpper(char* s) 
{ 
    string tmp(s); 

    // your code for a string applied to tmp 

    return tmp.c_str(); 
} 

你做!

+0

對不起,答覆很慢,但我將你的代碼複製到我的項目中,並有一些奇怪的語法錯誤? – Husky

+0

它現在可以工作,但在調用函數後字符串仍然保持不變。爲什麼會發生這種情況? – Husky

+0

這是我的錯誤。它現在可以工作,但輸出字符串並不如我預期的那樣。我認爲它應該是原始字符串的大寫字母? – Husky

相關問題