VC里如何调用C#写的dll ???
解决方案 »
- MFC焦点问题
- 一行批处理,如何转移到shellexecute中执行?
- 100分求Microsoft Windows 2000 服务器端应用程序开发设计指南的源代码
- 请教一个关于编辑框显示的问题
- 如何获得已加入多播组的IP及雄姿英发端口:
- 用IsWindow还是用FromHandle?
- 关于CListView的问题
- 在线等
- 在哪里能够找到好的电子表格控件
- cvWriteString中写入的字符串为什么不能包含有下划线等标点符号
- 在桌面上点击某个文件的右键,有一个选择“发送到”菜单,如何在“发送到”菜单中添加一个自己定义的子菜单?
- PostMessage与DispatchMessage有什么不同?
http://topic.csdn.net/t/20051027/16/4354580.html
C++ 文件 COMClient.cpp,它创建可执行客户端 COMClient.exe。
文件 1:CSharpServer.cs
// CSharpServer.cs
// compile with: /target:library
// post-build command: regasm CSharpServer.dll /tlb:CSharpServer.tlbusing System;
using System.Runtime.InteropServices;
namespace CSharpServer
{
// Since the .NET Framework interface and coclass have to behave as
// COM objects, we have to give them guids.
[Guid("DBE0E8C4-1C61-41f3-B6A4-4E2F353D3D05")]
public interface IManagedInterface
{
int PrintHi(string name);
} [Guid("C6659361-1625-4746-931C-36014B146679")]
public class InterfaceImplementation : IManagedInterface
{
public int PrintHi(string name)
{
Console.WriteLine("Hello, {0}!", name);
return 33;
}
}
}
文件 2:COMClient.cpp
// COMClient.cpp
// Build with "cl COMClient.cpp"
// arguments: friend#include <windows.h>
#include <stdio.h>#pragma warning (disable: 4278)// To use managed-code servers like the C# server,
// we have to import the common language runtime:
#import <mscorlib.tlb> raw_interfaces_only// For simplicity, we ignore the server namespace and use named guids:
#if defined (USINGPROJECTSYSTEM)
#import "..\RegisterCSharpServerAndExportTLB\CSharpServer.tlb" no_namespace named_guids
#else // Compiling from the command line, all files in the same directory
#import "CSharpServer.tlb" no_namespace named_guids
#endif
int main(int argc, char* argv[])
{
IManagedInterface *cpi = NULL;
int retval = 1; // Initialize COM and create an instance of the InterfaceImplementation class:
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(CLSID_InterfaceImplementation,
NULL, CLSCTX_INPROC_SERVER,
IID_IManagedInterface, reinterpret_cast<void**>(&cpi)); if (FAILED(hr))
{
printf("Couldn't create the instance!... 0x%x\n", hr);
}
else
{
if (argc > 1)
{
printf("Calling function.\n");
fflush(stdout);
// The variable cpi now holds an interface pointer
// to the managed interface.
// If you are on an OS that uses ASCII characters at the
// command prompt, notice that the ASCII characters are
// automatically marshaled to Unicode for the C# code.
if (cpi->PrintHi(argv[1]) == 33)
retval = 0;
printf("Returned from function.\n");
}
else
printf ("Usage: COMClient <name>\n");
cpi->Release();
cpi = NULL;
} // Be a good citizen and clean up COM:
CoUninitialize();
return retval;
}
输出
可以用以下命令行调用可执行客户端:COMClient <name>,其中 <name> 表示要使用的任何字符串,如 COMClient friend。Calling function.
Hello, friend!
Returned from function.
在示例 IDE 项目中,将项目“属性页”中的“命令行参数”属性设置为需要的字符串(例如,“friend”)。