本文介绍了在C#中调用C ++ dll中的向量参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我有一个用C ++创建一个dll文件的功能,这是:

Hello,
I have a function to create a dll file with C++, this is:

#include "stdafx.h"
#include <vector>
using namespace std;

void _stdcall fn(vector<double> &p, int* pLength)
{
    int i=0;
    double p_=0;
    do
    {
        p.push_back(p_);
        p_=2*p_+1;
        i++;
    }
    while (a condition of p_);    // The condition of loop....

    *pLength=i;

    return;
}





我成功编译了它。 (testFile.dll)。

在C#中,我将此函数调用如下:



I compile it successfuly. (testFile.dll).
In C#, I call this function as follows:

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(List<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].....
            List<double> p = new List<double>();
            int pLength = 0;
            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();
        }
    }
}





成功建立。当我跑步时,我收到一个错误:



Build successfuly. When I run, I get an error:

Cannot marshal 'parameter #1': Generic types cannot be marshaled.





at



at

fn(p, ref pLength);







如何修复此错误并获得正确的结果?谢谢。




How to fix this error and to get correct result? Thanks.

推荐答案

#include "stdafx.h"
#include <vector>
using namespace std;

int _stdcall fn(double list[], int length)
{
    if (length < 20)
        return 0;

    double value = 0.f;
    for (int i = 0; i < 20; i++)
    {
        list[i] = value;
        value = value*2+1;
    }
    return 20;
}
</vector>





导入声明如下:





Import declared like so:

[DllImport("testFile.dll")]
public static extern int fn(double[] list, int length);





从C#调用函数如下:





Call the function from C# like so:

double[] list = new double[20];
int length = 0;
length = fn(list, list.Length);





在此示例中,返回值0表示列表太小了。



In this example, a return value of 0 means the list is too small.


这篇关于在C#中调用C ++ dll中的向量参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 10:17