如何将使用dotnet-core构建的DLL与Python集成

时间:2019-07-05 19:42:38

标签: c# linux python-3.x .net-core ctypes

在Linux上使用Dotnet Core生成DLL(成功后)之后,我尝试使用ctypes提供的连接通过DllExport通过Python调用它,如下所示例如here

如何解决此问题?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices; // Calling conventions
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using RGiesecke.DllExport;

public class FormManager3
{
        [DllExport("test", CallingConvention = CallingConvention.Cdecl)]
        public static void Main() {
            Console.WriteLine("Test");
        }

       ...
}
cSharp = os.path.join(scriptDirectory, "legacy/bin/Debug/netcoreapp2.2/legacy.dll")
writeToCSharp = ctypes.cdll.LoadLibrary(cSharp)
writeToCSharp.test()

运行脚本后:

E   OSError: /home/farm/Documents/project/legacy/bin/Debug/netcoreapp2.2/legacy.dll: invalid ELF header

1 个答案:

答案 0 :(得分:0)

由于@MarkTolonen,我得以纠正我的错误。使用pythonnetmono,还将项目从控制台更改为类库,并删除DllExport

我设法按预期运行:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace legacy
{
    public class FloatLicManager3
    {
        public static int TestExport(int left, int right)
        {
            return left + right;
        }
    }
}

使用以下方法构建它:

dotnet build --runtime linux-x64

并用作:

import os
import clr

scriptDirectory = os.path.dirname(os.path.abspath(__file__))
cSharp = os.path.join(scriptDirectory, "legacy/bin/Debug/netstandard2.0/linux-x64/legacy.dll")
clr.AddReference(cSharp)

from legacy import FloatLicManager3

testing = FloatLicManager3()
testing.TestExport(1, 2)