c# - 通过在 C# GUI 中按下按钮调用 C++ DLL

标签 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 的名称是“FDD_DLL”

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
        }
    }
}

最佳答案

你会想要使用 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 .

关于c# - 通过在 C# GUI 中按下按钮调用 C++ DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943656/

相关文章:

c# - 在哪里可以找到 Microsoft.Build.Utilities.v3.5

c# - Expression.Quote() 能做哪些 Expression.Constant() 不能做的事?

javascript - 使用两个不同的 js 从一个 HTML 页面发送到另一个

c# - 如何处理作为参数传递给方法的 Lambda 表达式 - C# .NET 3.5

c++ - C++中按引用和值传递

c++ - 在 MSVC 2010 上 boost STATIC_ASSERT

c++ - 使用基本模板标识符时继承

ios - 如何添加多行按钮?

layout - SWT更新/重绘/布局问题

c# - Javascript 和 C# 中 var 实现的区别