PDA

View Full Version : استفاده از C DLL در C#



behnia_k
دوشنبه 18 بهمن 1395, 09:53 صبح
چط.ر از dll هایی که برای c یا C++‎‎ هستند در سی شارپ استفاده کنیم

behnia_k
دوشنبه 18 بهمن 1395, 16:00 عصر
من با vc 2008 یک Console application ساختم که نوع آنرا DLL مشخص کردم و دو فایل my_dll.h و my_dll.cpp را به شکل زیر به آن اضافه کردم





//my_dll.h
#include "stdafx.h"
#pragma once

#ifdef MY_DLL_EXPORTS
#define MY_DLL __declspec(dllexport)
#else
#define MY_DLL __declspec(dllimport)
#endif

namespace my_dll
{
class CMyClass
{
public:
// Returns a + b
static MY_DLL double Add(double a, double b);
// Returns a * b
static MY_DLL double Multiply(double a, double b);
// Returns a + (a * b)
static MY_DLL double AddMultiply(double a, double b);
};
}





// my_dll.cpp
//
#include "stdafx.h"
#include "my_dll.h"

namespace my_dll
{
double CMyClass::Add(double a, double b)
{
return a + b;
}
double CMyClass::Multiply(double a, double b)
{
return a * b;
}
double CMyClass::AddMultiply(double a, double b)
{
return a + (a * b);
}
}



این برنامه کمپایل و خروچی my_dll.dll را تولید کرد.
حال در سی شارپ گفتم اگر button1 زده شد فانکشن Add را صدا کند.



namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);

[DllImport("my_dll.dll")]
public static extern double Add(double a, double b);

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
double a = 100;
double b = 200;
double c = 0;
//
c = a + b;
//
c = Add(a, b);
String s;
//
s = " "
+ Convert.ToString(a)
+ " + "
+ Convert.ToString(b)
+ " = "
+ Convert.ToString(c);
//
MessageBox(0, s, "API Demo", 0);
}
}
}


والی هنگام اجرا خطای زار را میدهد

An unhandled exception of type 'System.EntryPointNotFoundException' occurred in
WindowsFormsApplication1.exe

Additional information: Unable to find an entry point named 'Add'
in DLL 'my_dll.dll'