简体   繁体   中英

how do you import a C .DLL file to a C# windows form application and call its functions that are defined in headers?

I'm new to programming and I'm basically trying to pull a third party .dll file written in C into C# code and then output one of its functions to an interface. Below is the function declaration in the header file used by the .DLL. I think I have to redefine it in C# as it cant use C headers.

int SPI_GetNumChannels(int *numChannels);

Here is my C# code

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public class App
        {
          [DllImportAttribute(@"C:\Users\Documents\libMPSSE.dll", EntryPoint = "SPI_GetNumChannels")]
          public static extern int SPI_GetNumChannels(ref int numChannels);
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = numChannels.ToString();
        }
    }
}

Am I on the right track here at all? I know the last line is not correct, any help would be greatly appreciated!

It's a good habit to put the external methods in a separate static class called NativeMethods or UnsafeNativeMethods.

Then, you were already very close.

int channels = 0;
NativeMethods.SPI_GetNumChannels(ref channels);
textBox1.Text = channels.ToString();

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