如何从C ++ DLL中传递C#函数中未知大小的数组? [英] How to pass an array with unknown size in C# function from C++ dll?

查看:74
本文介绍了如何从C ++ DLL中传递C#函数中未知大小的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个C ++ dll文件,其中包含一个名为fn(double * p,int * pLength)的导出函数,其中,p是一个指针(是一个用于的out数组) C#),在此函数中计算的pLength是p的长度(大小)。代码在这里:

Hi all,
I have a C++ dll file which contains an exported function named fn(double* p, int* pLength), where, p is a pointer (is an out array used in C#), pLength which is calculated in this function is the length (size) of p . Code here:

void _stdcall fn(double* p, int* pLength)
{
    int i=0;
    double p_=0;
    do
    {
        p[i]=p_;
        p_=an expression!!!!!;
        i++;
    }
    while (p_<20);

    *pLength=i;

    return;
}



我成功编译成dll文件。这个文件命名为testFile.dll并将其移动到System32文件夹。

现在,我启动C#控制台项目并从testFile.dll声明导出的函数fn(),此代码为:




I compile to dll file successfuly. This file is named "testFile.dll" and move it to System32 folder.
Now, I start C# console project and declare that exported function fn() from "testFile.dll", and this code is:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("testFile.dll")]
        public static extern void fn(double[] p, ref int pLength);
        static void Main(string[] args)
        {
            // I want to declare an array with unknown length (size),
            // because the length is calculated from fn() function!!!
            // And pass to fn() function to get p[i].....
            double[] p;
            int pLength;
            fn(p, ref pLength);

            // Display pLength and p[i]
            Console.WriteLine(pLength);
            for (int i = 0; i < pLength; i++)
                Console.WriteLine(p[i]);
            Console.ReadKey();
        }
    }
}





我跑步并得到两个错误:

错误1使用未分配的局部变量'p'

错误2使用未分配的局部变量'pLength'



如何修复他们?,我想从testFile.dll中的fn()函数中完全获得pLength和p [i]。在此先感谢。



I run and get two errors:
Error 1 Use of unassigned local variable 'p'
Error 2 Use of unassigned local variable 'pLength'

How to fix them?, and I want to get pLength and p[i] fully from fn() function in "testFile.dll". Thanks in advance.

推荐答案

您已声明 p 作为数组引用,但您没有创建实际的阵列在哪里。您必须在C#代码中创建它,并为DLL提供足够的空间,或者在尝试使用值填充DLL之前在DLL中创建它。
You have declared p as an array reference, but you do not create the actual array anywhere. You must create it in the C# code, and allow enough space for the DLL, or create it in the DLL before trying to fill it with values.


这篇关于如何从C ++ DLL中传递C#函数中未知大小的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆