Tuesday, September 13, 2022

Swift call C++ code and class

 [Reference]

https://stackoverflow.com/questions/35229149/interacting-with-c-classes-from-swift

https://stackoverflow.com/questions/2045774/developing-c-wrapper-api-for-object-oriented-c-code/2045860

Swift can not call C++ code directly. C++ code must be wrapped by C, Objective-C or Objective-C++. Swift uses the wrapper (wrapped code) to call C++ code. According to the references, an example is shown as the following:

C++ header (MPoint3.hpp)

#pragma once
class MPoint3
{
public:
    double x;
    double y;
    double z;
};

C wrapper header (MPoint3C.h)

#ifndef MPoint3C_h
#define MPoint3C_h

#ifdef __cplusplus
extern "C" {
#endif

typedef struct
{
    double x;
    double y;
    double z;
} MPoint3C;

MPoint3C* MPoint3_Constructor(void);
void MPoint3_Destructor(MPoint3C*);

#ifdef __cplusplus
}
#endif

#endif


C++ source (MPoint3C.cpp)

#include "MPoint3.hpp"
#include "MPoint3C.h"

#ifdef __cplusplus
extern "C" {
#endif

MPoint3C* MPoint3_Constructor(void)
{
	return (MPoint3C*) new MPoint3;
}

void MPoint3_Destructor(MPoint3C* ppt)
{
	delete (MPoint3*)ppt;
}

#ifdef __cplusplus
}
#endif


Use in Swift (swift.swift)

let pPt = MPoint3_Constructor()   // The type of pPt is UnsafeMutablePointer<MPoint3C>

pPt.pointee.x = 10
pPt.pointee.y = 11
pPt.pointee.z = 12

MPoint3_Destructor(pPt)


No comments:

Post a Comment

[Qt] 執行檔需要哪些 Dll?

 1. 使用 Qt  的 windeployqt.exe 工具 (在 C:\Qt\Qt5.14.1\5.14.1\msvc2017\bin\)。   a. 把執行檔 myProgram.exe 放在某個資料夾。   b. 在檔案總管這個資料夾按 Shift 和滑鼠右鍵,開啟 Po...