C# CALL CodeBlocks DLL(X64) 傳入/回傳字串(LPCSTR -> char*)
C# CALL CodeBlocks DLL(X64) 傳入/回傳字串(LPCSTR -> char*)
GITHUB:https://github.com/jash-git/CS-CALL-CodeBlocks-DLL
CB_BaseLib/main.h
#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
/* To use this exported function of dll, include this header
* in your project.
*/
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
void DLL_EXPORT SomeFunction(const LPCSTR sometext);
LPCSTR DLL_EXPORT SomeFunction01(const LPCSTR sometext);
double DLL_EXPORT Add(double a, double b);//test_API
#ifdef __cplusplus
}
#endif
#endif // __MAIN_H__
CB_BaseLib/main.cpp
#include <iostream>
#include "main.h"
#include "stdio.h"
#define LogFile "BaseLib.log"
static int g_intDebug=1;
using namespace std;
// a sample exported function
void WriteLog(const char *Msg,int state)
{
if(g_intDebug==1)
{
FILE *pf=NULL;
if(state==1)
{
pf=fopen(LogFile,"w");
}
else
{
pf=fopen(LogFile,"a");
}
fprintf(pf,Msg);
fprintf(pf, "\n");
fclose(pf);
}
}
void DLL_EXPORT SomeFunction(const LPCSTR sometext)
{
MessageBoxA(0, sometext, "DLL Message", MB_OK | MB_ICONINFORMATION);
}
LPCSTR DLL_EXPORT SomeFunction01(const LPCSTR sometext)
{
string Text = string(sometext);
Text+=" by jash.liao";
return Text.c_str();
}
double DLL_EXPORT Add(double a, double b)//test_API
{
WriteLog("\t Add API...",0);
return a + b;
}
extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// attach to process
// return FALSE to fail DLL load
break;
case DLL_PROCESS_DETACH:
// detach from process
break;
case DLL_THREAD_ATTACH:
// attach to thread
break;
case DLL_THREAD_DETACH:
// detach from thread
break;
}
return TRUE; // succesful
}
C#
using System;
using System.Runtime.InteropServices;
public class Program
{
[DllImport("CB_BaseLib.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall, EntryPoint = "SomeFunction")]
static extern void SomeFunction(String StrMsg);
[DllImport("CB_BaseLib.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall, EntryPoint = "SomeFunction01")]
static extern IntPtr SomeFunction01(String StrMsg);
[DllImport("CB_BaseLib.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall, EntryPoint = "Add")]
static extern double Add(double A,double B);
static void Pause()
{
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
public static void Main()
{
try
{
SomeFunction("中文 123456 ABCD");
Console.WriteLine("SomeFunction01():" + Marshal.PtrToStringAnsi(SomeFunction01("中文 ABCD 123456")));
Console.WriteLine("Add():" + Add(100,200));
}
catch (Exception e)
{
Console.WriteLine("C# ERROR" + e.ToString());
}
Pause();
}
}