通过按下C#GUI中的按钮来调用C ++ DLL

时间:2014-07-24 20:46:41

标签: c# c++ button dll dllimport

我有一个带有以下C ++导出函数的DLL:

    extern "C" __declspec(dllexport)
void*OPS_FDD(const char* char_Address,const int int_NumChann,const int int_SamplingFreq){
    FDD* FDD_Ptr_Object=NULL;
    if(FDD_Ptr_Object==NULL){// if condition to avoid memory leak
        FDD_Ptr_Object=new FDD(char_Address,int_NumChann,int_SamplingFreq);
    }
    if(FDD_Ptr_Object==NULL){
        //throw "allocate memory to FDD object pointer: could not be done";// can not throw inside __declspec(dllexport) functions marked extern "C"
        std::cout<<"Error: allocate memory to FDD object pointer: could not be done"<<'\n';
        system("pause");
    }
    delete FDD_Ptr_Object;// de-allocate the pointer to avoid memory leak
    FDD_Ptr_Object=NULL;// set the pointer to NULL
    return NULL;
}

现在我想通过按下C#GUI中的按钮来调用此DLL。我应该在以下可用于向按钮添加代码的空间中编写哪些代码行。顺便说一句,我的DLL的名称是&#34; FDD_DLL&#34;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace callDLL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // what lines of code should be here to call my C++ DLL
            // by pushing this C# GUI button ???
            // by the way, the name of my DLL is FDD_DLL
        }
    }
}

1 个答案:

答案 0 :(得分:1)

你会想要使用P / Invoke,如下所示:

 [DllImport( "FDD.DLL" )]
 private static extern IntPtr OPS_FDD( [MarshalAs( UnmanagedType.LPStr )] string char_Address, int int_NumChann, int int_SamplingFreq );

然后您可以像其他方法一样调用或多或少。现在的事情是你如何声明extern都取决于不同的参数意味着什么。例如,在这种情况下,char_Address可以通过几种方式传递给C ++ dll - 表示字符串的几种不同方式,如果它甚至意味着是一个字符串,那就是。 MarshalAs属性用于指定您想要的内容。没有更多信息,这是我最好的猜测。

有更多信息here