将带有非托管导出的C#DLL加载到Python中

2024-09-30 16:20:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用NuGet包UnmanagedExports构建了一个C#DLL(MyTestDll):

[DllExport("Test", CallingConvention = CallingConvention.Cdecl)]
public static string Test(string name)
{
    return "hi " + name + "!";
}

我通过ctypes DLL导入从Python中使用它:

^{pr2}$

这只是一个幻想,很管用。在

然后,我又添加了一个DLL(NoSenseDll):

namespace NoSenseDll
{
    public class NoSenseClass
    {
        public static int Sum(int a, int b)
        {
            return a + b;
        }
    }
}

我开始使用这个NoSenseDll来实现MyTestDll:

[DllExport("Test", CallingConvention = CallingConvention.Cdecl)]
public static string Test(string name)
{
    return NoSenseDll.NoSenseClass.Sum(4, 5).ToString();
}

不幸的是,它不起作用。Python说:

WindowsError: [Error -532462766] Windows Error 0xE043435

我曾试图将C:\\Temp\\Test添加到path,但这没用。在


我写过C++测试:

#include "stdafx.h"
#include "windows.h"
#include <iostream>
#include <string>
#include "WinBase.h"

typedef char*(__stdcall *f_funci)(const char*);

int _tmain(int argc, _TCHAR* argv[])
{
    int t;
    std::string s = "C:\\Temp\\Test\\MyTestDll.dll";
    HINSTANCE hGetProcIDDLL = LoadLibrary(std::wstring(s.begin(), s.end()).c_str());

    f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "Test");

    std::cout << "funci() returned " << funci(std::string("qqq").c_str()) << std::endl;
    std::cin >> t;
    return EXIT_SUCCESS;
}

如果第二个DLL(NoSeNSEDL)与C++可执行文件处于相同的文件夹中,则可以工作。如果我只是将NoSenseDll文件夹添加到PATH中,它就不起作用了。在


Tags: nameteststringreturnincludestaticpublicint
3条回答

草案解决方案:

  1. 将NoSenseDll复制到Python的文件夹,在我的例子中是%HOMEPATH%\Anaconda。在
  2. 重新启动IPython/Spyder。在

最终解决方案:

static MyTestDllClass() // static constructor
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder);
}
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
    string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    string assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
    if (File.Exists(assemblyPath) == false) return null;
    Assembly assembly = Assembly.LoadFrom(assemblyPath);
    return assembly;
}

最后一点:

如果因为matplotlib或pandas而无法使用IronPython,
如果你不能使用python.net因为IPython或spyder,
如果您不想使用COM互操作只是因为,
你真的想让C和Python协同工作,使用上面的解决方案和C反射。在

你不能直接用托管代码来做。 从dll注册COM对象:

%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm.exe my.dll /tlb:my.tlb /codebase

从python调用com。 请看这里的例子:http://www.codeproject.com/Articles/73880/Using-COM-Objects-in-Scripting-Languages-Part-Py

你也可以退房科斯图拉。福迪. 在

这是一个构建任务,它将把依赖项作为资源添加到程序集中,甚至挂接模块初始值设定项以在运行时加载它们。在

相关问题 更多 >