?
Solved

int** and native Dlls (double pointers,unsafe code etc)

Posted on 2006-04-09
10
Medium Priority
?
1,437 Views
Last Modified: 2008-03-10
I have to use a native dll that takes a int** as a parameter.

I have linked the dll function correctly ....

  [DllImport(DllPath, CallingConvention = CallingConvention.Cdecl)]
        public static extern int *MethodName(int** x,int n,char* filename);

But I can't for the life of me work out how to make a double pointer in c#.  I can do it for a single array and single pointer ...

int[] sarray = new int[1];
fixed (int* sptr = sarray)
{
}  

I have built a 2d array of ints

int[][] data = new int[n][];

and  I loop through a populate etc

Now how do I get a int** from this?

fixed (int** dptr = data)
{}  ????????????

0
Comment
Question by:tristan256
  • 5
  • 4
10 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16411584
Have you just tried passing "data" to the function ? If its a 2D array then the name of the array should also be a pointer-to-pointer to the first block in the second dimension.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16411679
The answer depends on the way unmanaged function treats int** parameter. It can be pointer to contingous memory block n*m*sizeof(int) - static array, or array of int* pointers (dynamic array). Assuming that this is continguous array, you can make unmanaged memory block with n*m integers and pass pointer to it to unmanaged function.

IntPtr array = Marshal::AllocHGlobal(Marshal::SizeOf(typeof(int))*n*m);

This line allocates unmanaged block for  n*m integers. Now you can fill this block line by line using one of the following ways:
- using Marshal.WriteInt32 Method (IntPtr, Int32, Int32), changing offset from 0 to (n*m-1)*Marshal::SizeOf(typeof(int))
- using Marshal.Copy Method (Int32[], Int32, IntPtr, Int32), copy single-dimentional managed array to unmanaged.

First parameter of MethodName function should have IntPtr type, pass array variable to function.
Replace char* filename with string filename, with CharSet = ANSII.
Replace int* return type to IntPtr and read result using Marshal.ReadInt32 method.

Don't forget to release array after using with Marshal::FreeHGlobal method.
Notice that of this is dynamic array, you need another algorithm.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16411719
If you have code of MethodName function or unmanaged code which calls it, please post this code. This gives enough information to write C# client code.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:tristan256
ID: 16411761
Yeah I tried just passing the array hoping it would marashal it for me but I get this error ...

"Cannot marshall parameter #1': There is no marshalling support for nested arrays."

I will find out exactly what the dll is doing and post some of the code.

0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16411768
.NET interoperability is based on marshalling data between managed and unmanaged memory. It is implemented using Marshal class functions, which are easy to understand for programmer with C++ experience.
Unsafe pointers support in C# is restricted and I don't suggest to use it for interoperability. Read about Marshal class in MSDN , I hope this can help. You can post more code if necessary.
0
 

Author Comment

by:tristan256
ID: 16414071
OK I've found out its contiguous.  

Haven't got any code to post yet, but I will give your suggestions a go and read about the Marshall class.  
0
 

Author Comment

by:tristan256
ID: 16416981
ok so I did this ...

change the method ...

        [DllImport(DllPath, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern void calibrate(IntPtr x, int n, int k, string filename);

Now build the pointer the unmagaed memory ...

 IntPtr DataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int))*NumberOfPixels*ColourDimensions);

for (i = 0; i < NumberOfPixels; i++)
                for(j = 0; j < ColourDimensions; j++)
                    Marshal.WriteInt32(DataPtr, i + j, data[i][j]);

But get this error ...

Attempted to read or write protected memory.  This is often an indication the memory is corrupt.

Any suggestions?
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 16417074
Try this:

int offset = 0;

for (i = 0; i < NumberOfPixels; i++)
{
                for(j = 0; j < ColourDimensions; j++)
                {
                    Marshal.WriteInt32(DataPtr,offset, data[i][j]);
                    offset += Marshal.SizeOf(typeof(int));
                }
}

I will test this now.
0
 
LVL 48

Accepted Solution

by:
AlexFM earned 2000 total points
ID: 16417140
The following test succeeded:

    class Program
    {
        static int[,] intArray = new int[5, 10];

        static void Main(string[] args)
        {
            IntPtr DataPtr = Marshal.AllocHGlobal(
                Marshal.SizeOf(typeof(int)) *
                intArray.GetLength(0) *
                intArray.GetLength(1));

            int offset = 0;

            for (int i = 0; i < intArray.GetLength(0); i++ )
            {
                for (int j = 0; j < intArray.GetLength(1); j++ )
                {
                    Marshal.WriteInt32(DataPtr, offset, intArray[i, j]);
                    offset += Marshal.SizeOf(typeof(int));
                }
            }

            Marshal.FreeHGlobal(DataPtr);
        }
    }
0
 

Author Comment

by:tristan256
ID: 16577426
Ooops! Sorry, forgot to accept the answer, worked great.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question