如何调用从Win32进程一个.NET的DLL? [英] How to call a .NET dll from a win32 process?

查看:287
本文介绍了如何调用从Win32进程一个.NET的DLL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么选择,当涉及到使用.NET的DLL从Win32进程? 我需要基本使用C#DLL从Win32进程。

What are the options when it comes to using a .NET dll from a win32 process? I need to basically use a C# dll from a Win32 process.

我有一个可能的解决方案,现在,需要添加C#的dll到GAC(使用RegAsm.exe),然后调用C#DLL通过COM包裹调用。 但是,这种解决方案是pretty的沉重。它要求.NET的DLL被添加到GAC上都应该运行此Win32进程的所有机器。

I have a possible solution right now that requires adding the C# dll to the GAC (using RegAsm.exe), then calling the C# dll via COM wrapped calls. However that solution is pretty heavy. It requires that the .NET dll be added to the GAC on all machines that are supposed to run this win32 process.

有没有可能做到这一点,而无需调用RegAsm能够使用C#DLL之前?

Would it be possible to do this without having to call 'RegAsm' prior to being able to use the C# dll?

推荐答案

您可以使用免注册COM与.NET COM组件 - 看的这里

You can use registration-free COM with .NET COM components - see here.

另一种选择是使用C ++ / CLI的桥梁。人们大多熟悉使用它来包装非托管的API暴露给管理code,但它实际上是双向的 - 它可以编译 / CLR ,和但产生 .DLL 组装用普通非托管的出口,这可以从非托管code像往常一样被调用。这里是一个非常简单的例子,暴露了系统::字符串:: ToUpper的这种方式:

Another option is to use C++/CLI as a bridge. People are mostly familiar with using it to wrap unmanaged APIs to expose to managed code, but it actually works both ways - it is possible to compile with /clr, and yet produce a .dll assembly with plain unmanaged exports, which can be called from unmanaged code as usual. Here's a very simple example that exposes System::String::ToUpper that way:

// compile with cl.exe /clr /LD wrapper.cpp ole32.lib

#include <windows.h>

__declspec(dllexport)
wchar_t* ToUpper(const wchar_t* wcs)
{
    System::String^ s = gcnew System::String(wcs);
    array<wchar_t>^ chars = s->ToUpper()->ToCharArray();

    size_t size = chars->Length * 2;
    wchar_t* dst = (wchar_t*)CoTaskMemAlloc(size + 2);
    pin_ptr<wchar_t> src = &chars[0];
    memcpy(dst, src, size);
    dst[chars->Length] = 0;
    return dst;
}

这将产生 wrapper.dll - 混合托管/非托管组件 - 和导出库 wrapper.lib 。后者可以在纯原生应用程序被使用如下:

This will produce wrapper.dll - hybrid managed/unmanaged assembly - and an export library wrapper.lib. The latter can be used in a pure native application as follows:

// compile with cl.exe test.cpp ole32.lib wrapper.lib
// note, no /clr

#include <stdio.h>
#include <windows.h>

wchar_t* ToUpper(const wchar_t* wcs);

int main()
{
    wchar_t* s = ToUpper(L"foo");  
    wprintf(L"%s", s);
    CoTaskMemFree(s);
}

在实践中它会加载CLR运行到调用进程(除非它已经装载有),并从本地code到管理code透明调度 - 所有的魔法是由C ++ / CLI编译器完成

In practice it will load CLR runtime into the calling process (unless it's already loaded there) and dispatch from native code to managed code transparently - all the magic is done by C++/CLI compiler.

这篇关于如何调用从Win32进程一个.NET的DLL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆