将数组从Python传递到C#DLL而不使用不安全代码和本机C#数组

2024-04-23 08:40:16 发布

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

有谁知道一种更好的方法可以将数组从Python传递到C#DLL,而不必求助于不安全的C#代码,而且最好使用本机C#数组?另外,在Python中创建需要传递到C#DLL的数组类型而不必实例化每个元素,是否有更好或更干净的方法?在

我从python调用一个C库,如下所示:Calling a C# library from python。以下是我当前的C#DLL代码:

using System.Runtime.InteropServices;
using RGiesecke.DllExport;

namespace TestLib
{
    public class TestLib
    {
        [DllExport("running_sum", CallingConvention = CallingConvention.Cdecl)]
        unsafe public static int running_sum(double* running_sum, int n, double* values)
        {
            // check for errors and return error code
            if (n <= 0 || running_sum == null || values == null)
                return 1;

            running_sum[0] = values[0];
            int i = 1;
            while (i < n)
            {
                running_sum[i] = running_sum[i - 1] + values[i];
                i++;
            }

            // return success
            return 0;
        }
    }
}

下面是我的Python3.4代码调用这个C#DLL:

^{pr2}$

Tags: 方法代码return数组publicrunningintdll
1条回答
网友
1楼 · 发布于 2024-04-23 08:40:16

我不认为这是可能的,最近出现了CoreRT,它允许编译本机lib并在.netframework之外使用(实际上是.netcore)。它真的很酷,而且尽可能的好用。(仅适用于windows、linux和osx x64平台)

https://dev.to/encrypt0r/writing-native-libraries-in-c-3kl

相关问题 更多 >