Click here to Skip to main content
15,744,193 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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;
        p_=an expression!!!!!;
    while (p_<20);



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
        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]
            for (int i = 0; i < pLength; 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.
Updated 30-Mar-14 17:35pm

1 solution

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.
Share this answer
Andrewpeter 31-Mar-14 7:39am    
Thanks. But how to create space of p array in this dll? Hope you help me.
Andrewpeter 31-Mar-14 7:52am    
In fact, I will call this function twice to get pLength and re-allocate memory space for p:

double[] p = new double[2]; // Allocate with temporariness
int pLength = 0;
fn(p, ref pLength); // Get pLength correctly
p = new double[pLength]; // Re-allocate p correctly
fn(p, ref pLength); // Recall to get p.

But this work has loss "twice" with fn() function! I want to call once fn() function.

Thanks in advance.
Richard MacCutchan 1-Apr-14 3:32am    
You can allocate the array in the DLL using new and then copy that into managed memory space on return. Something like:

double[] fn(out int p);

Then in the DLL

double pArray[] = new double[number];
return pArray;

You may like to consider whether you really need this code in an unmanaged DLL.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900