文章目录
C#创建dll
IDE Microsoft Visual Studio2010
创建C#项目
运行项目
新建的项目属性是类库,项目右键 输出类型改为 windows应用程序,通过以下简单代码,F5直接运行
Console.WriteLine(“hahaha”) 类似java的system.out,直接在控制台输出语句
namespace ClassLibrary2test
{
public class Class1
{
static void Main()
{
Console.WriteLine("hahaha");
}
}
}
生成C# dll
将输出类型改为“类库”,ctrl + alt + F7 即可生成dll ,一般在/bin/Debug目录下
源码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpClassLibraryForJava
{
public class Class1
{
static void Main()
{
Console.WriteLine("Hello C# ");
Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);
Console.WriteLine(getstr());
Console.WriteLine(add(1,2));
}
public static string getstr()
{
String str = "hello,this is C#";
return str;
}
public static int add(int x, int y)
{
return x + y;
}
}
}
常见问题
不包含适合于入口点的静态“Main”方法
检查 Main() 首字母是否写,main是否拼写错误
指定输出32位或64位
无法直接启动带有“类库输出类型”的项目
将输出类型改为“windows”应用程序
C++创建dll
工具 Microsoft Visual Studio2017
创建C++项目
文件-新建项目
目录结构,main 为主入口
源码
#include "pch.h"
#include <iostream>
using namespace std;
extern "C" __declspec(dllexport) int add(int x,int y);
extern "C" __declspec(dllexport) const char* getstr();
extern "C" __declspec(dllexport) char* getstr2();
int main()
{
std::cout << "Hello World!\n";
cout << add(5, 80) << endl;
cout << getstr() << endl;
cout << getstr2() << endl;
}
int add(int x, int y) {
return x + y;
}
const char* getstr() {
const char* chars = "123";
return chars;
}
//乱码
char* getstr2() {
char c[] = "456";
return c;
}
运行项目 测试所写代码
按F5 可以直接运行,运行成功如下(忽略最后一行乱码)
如果出现以下内容
请检查 项目名称-右键属性 配置类型是否为exe
生成C++ dll
将配置类型改为 dll
ctrl + alt + F7 即可获得dll
一般在debug目录下