【问题标题】:Calling static function of C# .NET in C (ICLRRuntimeHost_ExecuteInDefaultAppDomain)在 C 中调用 C# .NET 的静态函数(ICLRRuntimeHost_ExecuteInDefaultAppDomain)
【发布时间】:2014-02-27 12:40:32
【问题描述】:

我有这个类KernelHelper,它是用 C# .NET Framework 2.0 编写的。我想做的是在 C 程序中调用它的静态函数。

namespace Kernel.Client {

    public class KernelHelper {

        public static int testc(string msg) {
            // Removing the message box does not change anything
            System.Windows.Forms.MessageBox.Show(msg);
            return 0;
        }

        // ...

    }
}

它编译并且到目前为止似乎没有产生任何问题。但是调用ICLRRuntimeHost_ExecuteInDefaultAppDomain() 返回0x80131513,这是根据this 我没有遵循正确的签名约定的事实。但这不可能是问题。

#if defined(_WIN32)
#   include <Windows.h>
#   define COBJMACROS
#   define CINTERFACE
#   include <mscoree.h>
#endif 

// ...

HRESULT status;
ICLRRuntimeHost *Host;
BOOL Started;
DWORD Result;

Host = NULL;
Started = FALSE;

status = CorBindToRuntimeEx(
             NULL,
             NULL,
             0,
             &CLSID_CLRRuntimeHost,
             &IID_ICLRRuntimeHost,
             (PVOID *)&Host
             );

if (FAILED(status)) {
    printf("failed 1\n");
}

status = ICLRRuntimeHost_Start(Host);
if (FAILED(status)) {
    printf("failed 2\n");
}

Started = TRUE;

status = ICLRRuntimeHost_ExecuteInDefaultAppDomain(
             Host,
             L"C:\\svn\\Server\\Kernel\\interface\\bin\\Kernel.Client.dll",
             L"Kernel.Client.KernelHelper",
             L"testc",
             L"My message",
             &Result
             ); 

if (FAILED(status)) {
    printf("failed 3\n");
}

有人可以帮我吗?

编辑: 我也试过没有消息框,让函数只返回0,但它没有改变任何东西。

【问题讨论】:

  • Table 7-2 列出了 ICLRRuntimeHost_ExecuteInDefaultAppDomain 的五个参数,但您提供了六个。
  • 我正在使用 C 接口。该函数的第一个参数是显式的this(主机)指针。
  • 尝试消息框以外的其他方法,例如写入日志。消息框意味着 Winforms、STA、消息泵等。或者,只需在其上放置一个断点。
  • 嗯,这是个好建议。我现在在没有使用消息框的情况下尝试了它.. 让它返回值 0。但变量Result 仍然包含0x80131513。我认为 .dll 可能无法正确加载,但我不知道这是否属实或可能是什么问题..

标签: c# .net visual-studio-2010 dll clr


【解决方案1】:

哇,没想到自己这么快就找到了解决方案。如果您遇到同样的问题,请尝试this。它似乎并不适合所有人。

我需要做的就是在我的项目属性中将Platform TargetAny CPU 更改为x86

编辑:如果有人可以向我展示另一个解决方案,我仍然会很高兴,因为我无法判断这是否不是问题,无论如何更改此设置。

【讨论】:

  • 嗯,我贴了主要信息,甚至还有截图给像我这样的老外。答案在这里 + 一个附加链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2013-05-28
  • 2019-12-07
  • 1970-01-01
相关资源
最近更新 更多