2012-11-22 116 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

相关问题