返回> 网站首页
C++调用C#的DLL以及BSTR类型转换
yoours2016-07-20 16:34:20
简介一边听听音乐,一边写写文章。
一、创建C#的DLL
创建C#类库DLL工程
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace TestInterface
{
[Guid("045ABA1B-E6E2-486c-9AFD-B595CBAE7877")]
[ComVisible(true)]
public interface INewInterface
{
[DispId(1)]
void Write(string str);
[DispId(2)]
string Read();
}
[Guid("090FD27B-BEAD-4aae-BF51-F6486042A3A0")]
[ClassInterface(ClassInterfaceType.None)]
public class Worker : INewInterface
{
public void Write(string str)
{
File.WriteAllText("C:\\comsharp.log", str);
}
public string Read()
{
return "123456abcdef";
}
}
}
把AssemblyInfo.cs中的[assembly:ComVisible(false)]改成[assembly: ComVisible(true)].右击项目名打开属性窗口,点标签Build,选中Register for COMinterop(为COM互操作注册).
二、C++程序调用
#import "..\TestInterface\bin\Release\TestInterface.tlb" named_guids raw_interfaces_only
using namespace TestInterface;
CoInitialize(NULL);
// 方法一
INewInterfacePtr my(__uuidof(Worker));
// 方法二
TestInterface::INewInterfacePtr my1;
my1.CreateInstance(TestInterface::CLSID_Worker); //实例化一个类
BSTR bstr;
String2BSTR("123456", &bstr);
my1->Write(bstr);my->Write(bstr);
BSTR bstr2;
my1->Read(&bstr2);
char* str=NULL;
BSTR2String(&bstr2, &str);
TRACE("%s", str);
delete[] str;
CoUninitialize();
三、类型转换
void String2BSTR(char* str, BSTR* bstrText)
{
*bstrText = _com_util::ConvertStringToBSTR(str);
}
void BSTR2String(BSTR* bstrText, char** str)
{
char* lpszText2 = _com_util::ConvertBSTRToString(*bstrText);
*str = new char[strlen(lpszText2)+1];
strcpy(*str, lpszText2);
delete[] lpszText2;
}
文章评论
2174人参与,0条评论