9

現在、アンマネージ C++ アプリから C# DLL の関数を呼び出そうとしています。

Web と SO で何時間も検索した後、いくつかのオプションがあることがわかりました。

COM を使用DllExportしたり、デリゲートでリバース PInvoke を使用したりできます。最後のが一番魅力的に聞こえたので、SOを検索した後、ここにたどり着きました。

記事にはリバース PInvoke の使用方法が示されていると記載されていますが、C# コードを使用するには、まず C++ Dll をインポートする必要があるようです。

最初に C# アプリを実行せずに、C++ を使用して C# Dll 関数を呼び出せるようにする必要があります。

リバースPInvokeはそれを行う方法ではないかもしれませんが、低レベルのものに関しては私はかなり経験が浅いので、これを行う方法に関するポインタやヒントは素晴らしいでしょう.

リンク先のコードは

C#

using System.Runtime.InteropServices;

public class foo    
{    
    public delegate void callback(string str);

    public static void callee(string str)    
    {    
        System.Console.WriteLine("Managed: " +str);    
    }

    public static int Main()    
    {    
        caller("Hello World!", 10, new callback(foo.callee));    
        return 0;    
    }

    [DllImport("nat.dll",CallingConvention=CallingConvention.StdCall)]    
    public static extern void caller(string str, int count, callback call);    
}

C++

#include <stdio.h>    
#include <string.h>

typedef void (__stdcall *callback)(wchar_t * str);    
extern "C" __declspec(dllexport) void __stdcall caller(wchar_t * input, int count, callback call)    
{    
    for(int i = 0; i < count; i++)    
    {    
        call(input);    
    }    
}
4

1 に答える 1

11

まあ、独自の CLR ホストをスピンアップして、必要なものを実行するだけです。

#include <mscoree.h>
#include <stdio.h>
#pragma comment(lib, "mscoree.lib") 

void Bootstrap()
{
    ICLRRuntimeHost *pHost = NULL;
    HRESULT hr = CorBindToRuntimeEx(L"v4.0.30319", L"wks", 0, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (PVOID*)&pHost);
    pHost->Start();
    printf("HRESULT:%x\n", hr);

    // target method MUST be static int method(string arg)
    DWORD dwRet = 0;
    hr = pHost->ExecuteInDefaultAppDomain(L"c:\\temp\\test.dll", L"Test.Hello", L"SayHello", L"Person!", &dwRet);
    printf("HRESULT:%x\n", hr);

    hr = pHost->Stop();
    printf("HRESULT:%x\n", hr);

    pHost->Release();
}

int main()
{
    Bootstrap();
}
于 2013-01-11T00:25:09.680 に答える