我有一个C# DLL文件,我通过导入相应的.tlb文件在我的.cpp文件中使用COM Interop将该DLL用于C++中,并且这样做完全没有问题。现在我想要在C语言中使用同样的DLL,但由于我无法在C程序中使用#import,那么我应该如何使用已经注册为COM组件的DLL?
这是一个包含3个文件的简单示例:
首先是C# DLL。它将被构建为一个DLL。
using System;
using System.Collections.Generic;
using System.Text;
namespace csdll
{
public class ReturnValues
{
public void CSGetInt(ref int x)
{
x = 42;
}
public void CSGetStr(ref string s)
{
s = "Hey it works";
}
}
}
#include <string>
#include <msclr\marshal_cppstd.h>
#using "csdll.dll"
using namespace System;
extern void cppGetInt(int* value)
{
csdll::ReturnValues^ rv = gcnew csdll::ReturnValues();
rv->CSGetInt(*value);
}
extern void cppGetStr(std::string& value)
{
System::String^ csvalue;
csdll::ReturnValues^ rv = gcnew csdll::ReturnValues();
rv->CSGetStr(csvalue);
value = msclr::interop::marshal_as<std::string>(csvalue);
}
现在是主程序。
#include "stdafx.h"
#include <iostream>
#include <string>
// These can go in a header
extern void cppGetInt(int* value);
extern void cppGetStr(std::string& value);
int _tmain(int argc, _TCHAR* argv[])
{
int value = 99;
std::string svalue = "It does not work";
cppGetInt(&value);
std::cout << "Value is " << value << std::endl;
cppGetStr(svalue);
std::cout << "String value is " << svalue << std::endl;
return 0;
}
将依赖项设置为DLL。 将构建平台设置为混合平台而不是win32或任何CPU。如果设置为其中任何一个,某些内容将无法构建。运行它,您将会得到
Value is 42
String value is Hey it works