本系列探討如何在 Windows Store Apps (C#) 中調用原生 C/C++ 代碼,並夯實 C 語言基礎。第一篇涵蓋 Windows Runtime Component 橋接機制、C 語言編譯設置、調試配置、UTF-8 保存模板,以及最經典的 Hello World。
UWP/WinRT 沙箱禁止直接加載普通 DLL,需封裝為 **Windows Runtime Component (wincpp)**,生成 `.winmd` 元數據文件,供 C#/JS/投影語言調用。
// NativeDll/Simple.h
#pragma once
namespace NativeDll {
public ref class Simple sealed {
public:
int Add(int x, int y);
};
}
// NativeDll/Simple.cpp
#include "pch.h"
#include "Simple.h"
using namespace NativeDll;
int Simple::Add(int x, int y) { return x + y; }
// NativeDemo/Simple.xaml.cs (C#)
using NativeDll;
var simple = new Simple();
int result = simple.Add(1, 1); // 2
C++/CX 關鍵字: `ref class`、`sealed`、`^` (handle)、`Platform::String^` 字符串類型。
#ifndef _MYHEAD_HELLO_
#define _MYHEAD_HELLO_
#ifdef __cplusplus
extern "C" {
#endif
char *demo_cHello(char *name);
#ifdef __cplusplus
}
#endif
#endif
#include "pch.h"
#include "cHello.h"
#include "cHelper.h" // 字符串輔助
char *demo_cHello(char *name) {
return str_concat2("hello: ", name);
}
/* main 函數說明:
int main(int argc, char *argv[]) {
// argc 含程序名,argv[0] 為程序名
return 0;
}
void main(void) 亦合法但非標準。*/
char *str_concat2(const char *s1, const char *s2); char *int_toString(int n);
實現細節見源碼下載,採用動態分配,調用者負責 `free`。