C# 在托管c++;类,该类从C调用,结果是';mydll';无法加载 我正在构建一个C++应用程序,它使用了一个非托管C++ DLL中的类。 我在非托管DLL周围创建了一个托管C++包装DLL。在非托管类中使用std::string时,运行程序时会出现未处理的异常。例外情况是“无法加载由“mydll”导入的过程”。下面是示例代码。当我从非托管头文件中删除std::string时,一切正常。 我正在使用VS2015,希望任何人都能帮我解决我做错的事情
问候 萨姆C# 在托管c++;类,该类从C调用,结果是';mydll';无法加载 我正在构建一个C++应用程序,它使用了一个非托管C++ DLL中的类。 我在非托管DLL周围创建了一个托管C++包装DLL。在非托管类中使用std::string时,运行程序时会出现未处理的异常。例外情况是“无法加载由“mydll”导入的过程”。下面是示例代码。当我从非托管头文件中删除std::string时,一切正常。 我正在使用VS2015,希望任何人都能帮我解决我做错的事情,c#,c++,c++-cli,C#,C++,C++ Cli,问候 萨姆 非托管C++头文件: class __declspec(dllexport) Student { private: char *_fullname; double _gpa; std::string _name2; public: Student(char *name, double gpa); ~Student(); double getGpa() const; char *getName()
非托管C++头文件:
class __declspec(dllexport) Student
{
private:
char *_fullname;
double _gpa;
std::string _name2;
public:
Student(char *name, double gpa);
~Student();
double getGpa() const;
char *getName() const;
};
非托管C++文件
#include "unman_class.h"
#include <cstring>
Student::Student(char* name, double gpa)
{
_fullname = new char[strlen(name + 1)];
strcpy(_fullname, name);
std::string klaas = "test";
//_name2 = name;
_gpa = gpa;
}
Student::~Student()
{
delete[] _fullname;
}
double Student::getGpa() const
{
return _gpa;
}
char* Student::getName() const
{
return _fullname;
}
C#代码
使用过时的非托管DLL副本运行C#项目很容易出错。避免手动复制文件,确保所有3个可执行文件都构建在同一目录中。这只需要将C#项目的生成目录从bin\Debug更改为..\Debug。或者确保构建后事件是完美的,并且始终复制最新版本。谢谢@HansPassant,这就是问题所在。
using namespace System;
#include "..\\unmanaged_dll\unmanaged_dll\unman_class.h"
namespace man_dll {
public ref class man_class
{
private:
Student *_stu;
public:
man_class(String ^fullname, double gpa)
{
_stu = new Student((char *)
System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(
fullname).ToPointer(),
gpa);
}
~man_class()
{
delete _stu;
_stu = 0;
}
property String ^Name
{
String ^get()
{
return gcnew String(_stu->getName());
}
}
property double Gpa
{
double get()
{
return _stu->getGpa();
}
}
};
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using man_dll;
namespace test_program
{
class Program
{
static void Main(string[] args)
{
var test = new man_class("test",10);
Console.WriteLine(test.Name);
Console.WriteLine(test.Gpa);
Console.ReadLine();
}
}
}