C#下调用C写的dll的例子

来源:互联网 发布:fgo石头号除了淘宝 编辑:程序博客网 时间:2024/06/11 01:17

初学c#,不明白怎么用指针调用C下的函数,经过一番学习,记录如下:

//===================dll_test.def====

LIBRARY "test_dll"
EXPORTS
addtest @ 1
addstring @ 2

 

///dll 主文件================================

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

int __stdcall addtest(int x, int y, int *z)
{
 *z = x + y;
 return x+y;
}
char *addstring(char **stringArray, char *string1, int numofarray)
{
 for(int i=0; i<numofarray; i++ )
 {
  strcat(string1, stringArray[i]);
 }
 return string1;
}


int main(void)
{
 return 0;
}

//=========================================================

 

//=========c#调用dll的方法:===========================


        [System.Runtime.InteropServices.DllImport("D://2009lab//0902//090208//testcsp_output//Debug//test_dll.dll")]
        static extern int addtest(int x, int y, IntPtr z);
        [System.Runtime.InteropServices.DllImport("D://2009lab//0902//090208//testcsp_output//Debug//test_dll.dll")]
        static extern IntPtr addstring(IntPtr[] stringArray, IntPtr string1, int numofarray);
        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr outz = Marshal.AllocHGlobal(sizeof(int));
            int x = 2;
            int y = 4;
            int zp = 0;
            int z = addtest(x, y,outz);
            zp = Marshal.ReadInt32(outz);
            this.textBox1.Text = zp.ToString();
            Marshal.FreeHGlobal(outz);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            const int num_of_vars = 7;
            IntPtr [] strArray = new IntPtr[num_of_vars + 1];
            for (int i = 0; i <=num_of_vars; i++)
            {
                string s = i.ToString();
                strArray[i] = Marshal.StringToHGlobalAnsi(s);
            }
            //strArray[num_of_vars] = 0;

            IntPtr outstring = Marshal.AllocHGlobal(100);
            for (int i = 0; i < 100; i++)
            {
                Marshal.WriteByte(outstring, i, 0);
            }
            addstring(strArray, outstring, num_of_vars);
            this.textBox2.Text = Marshal.PtrToStringAnsi(outstring);
            Marshal.FreeHGlobal(outstring);
            for (int i = 0; i <= num_of_vars; i++)
            {
                Marshal.FreeHGlobal(strArray[i]);
            }
        }