简体   繁体   中英

Calling C function with pointers from C#.NET code

I have the following issue:

I have to use an external DLL library written in C, which implements a function that two pointer as function inputs. I do not know how to do this from C#...Something like:

typedef struct{
double[3] dArray;
int a;
int b;
}myInput

[...]

myFunction(myInput *input)

I can define a similar struct in C#, but I cannot make my code works fine Is it possible todo this from C#? Thank you in advance!

Try code like this. I'm not sure of the sizes of the int and double. Int in c can be 16, 32, or 64. Double can be 4 or 8 (usually 8).

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

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("XXXXXXXX.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void myFunction(IntPtr input);

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct MyInput
        {
            [MarshalAs (UnmanagedType.ByValArray, SizeConst = 3)]
            double[] dArray;
            int a;
            int b;
        }

        static void Main(string[] args)
        {
            MyInput myInput = new MyInput();
            IntPtr dataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(myInput));
            Marshal.StructureToPtr(myInput, dataPtr, true);

            myFunction(dataPtr);

        }
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM