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

phpMyAdmin 無法存取 MariaDB 10 的解決方法

 [Reference]  https://www.qnap.com/zh-tw/how-to/faq/article/%E7%82%BA%E4%BB%80%E9%BA%BC%E7%84%A1%E6%B3%95%E5%9C%A8-phpmyadmin-%E5%AD%98%E5%8...