Skip to content

Instantly share code, notes, and snippets.

@toya33
Last active October 15, 2017 15:12
Show Gist options
  • Save toya33/35a184fb671ac95069c9cf8a402c4448 to your computer and use it in GitHub Desktop.
Save toya33/35a184fb671ac95069c9cf8a402c4448 to your computer and use it in GitHub Desktop.
C#からC++のDLLを呼び出す際の最低限の内容(文字列のマーシャリング含む)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// DllImportに必要
using System.Runtime.InteropServices;
namespace threadTester
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
//※これは必須:CallingConvention = CallingConvention.Cdecl
[DllImport("ThreadDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private extern static int DllEntryPint(StringBuilder test);
public MainWindow()
{
InitializeComponent();
}
// メインフォームにButton「ExecuteButton」、Label「resultLabel」を用意しておくこと
private void ExecuteButton_Click(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder(256);
sb.Append("test");
int retCode = DllEntryPint(sb);
resultLabel.Content = "ResultCode : " + retCode;
}
}
}
#pragma once
// ThreadDll.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "ThreadDll.h"
void ThreadManager::SetProperty(const wchar_t* name)
{
printf("in SetProperty!\n");
wcscat_s(_name, MAX_PATH, name);
}
void ThreadManager::Execute()
{
printf("in Execute!\n");
wprintf(L"args : %ls", _name);
}
int DllEntryPint()
{
return 11;
}
int DllEntryPint(LPCWSTR name)
{
printf("in DllEntryPint!\n");
//ThreadManager* tm = new ThreadManager();
//tm->SetProperty(name);
//tm->Execute();
return 11;
}
#pragma once
#include <stdio.h>
#ifdef THREADDLL_EXPORTS
#define THREADDLL_API __declspec(dllexport)
#else
#define THREADDLL_API __declspec(dllimport)
#endif
#define MAX_PATH 260
// 進捗管理用構造体
typedef struct {
wchar_t* name;
int max;
int current;
int status;
int result;
} STATUS_STRUCT;
// スレッド管理用クラス
class ThreadManager {
private:
wchar_t _name[MAX_PATH];
public:
STATUS_STRUCT* _status;
void SetProperty(const wchar_t* name);
void Execute();
};
// 外部参照関数
//extern "C" THREADDLL_API int DllEntryPint();
extern "C" THREADDLL_API int DllEntryPint(LPCWSTR name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment