您的位置:首页 > 编程语言 > C#

c编写dll供c#调用

2010-04-10 19:14 375 查看
1.新建dll工程,在函数前面增加 extern "C" __declspec(dllexport) double __stdcall

double 为函数返回值类型

// log.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#define PI 3.14159

double AverageRandom(double min,double max)//产生(min,max)之间均匀分布的随机数
{
int MINnteger = (int)(min*10000);
int MAXnteger = (int)(max*10000);
int aa=rand();
int bb=rand();
int randInteger = aa*bb;
int diffInteger = MAXnteger - MINnteger;
int resultInteger = randInteger % diffInteger + MINnteger;
return resultInteger/10000.0;
}
double LogNormal(double x,double miu,double sigma) //对数正态分布概率密度函数
{
return 1.0/(x*sqrt(2*PI)*sigma) * exp(-1*(log(x)-miu)*(log(x)-miu)/(2*sigma*sigma));
}
extern "C" __declspec(dllexport) double __stdcall  Random_LogNormal(double miu,double sigma,double min,double max)//产生对数正态分布随机数
{

double x;
double dScope;
double y;
do
{
x = AverageRandom(min,max);
y = LogNormal(x, miu, sigma);
dScope = AverageRandom(0, LogNormal(miu,miu,sigma));
}while( dScope > y);
return x;
}


2.C#中代码

//通过DllImport引用log.dll类。Random_LogNormal来自于log.dll类
[DllImport("log.dll", EntryPoint = "Random_LogNormal")]
public static extern double Random_LogNormal(double miu, double sigma, double min, double max);

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

class Program
{

///****************************************************
///    产生N=100个在(0,50)区间内满足对数正态分布的随机数
///*****************************************************/

const int N = 100;
const int MAX = 30;
const double MIN = 0.5;
const double MIU = 1.2;
const double SIGMA = 1;

//通过DllImport引用log.dll类。Random_LogNormal来自于log.dll类
[DllImport("log.dll", EntryPoint = "Random_LogNormal")]
public static extern double Random_LogNormal(double miu, double sigma, double min, double max);

static void Main()
{

int i, j;
for (i = 0, j = 0; i < N; i++)
{
double x = Random_LogNormal(MIU, SIGMA, MIN, MAX);
Console.Write(x);
Console.Write(' ');
j++;
if (j == 5)
{
Console.Write("/n");	//每行显示5个数
j = 0;
}

}
Console.ReadLine();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: