样本绑定示例#

此示例演示了如何为非Qt C++库生成Python绑定。

示例定义了一个CMake项目,该项目构建了两个库

  • libuniverse - 一个具有两个C++类的样本库。

  • Universe - 包含对上述库绑定的生成的Python扩展模块。

项目文件的结构方式允许用户将其复制粘贴到自己的项目中,并能够通过最小的修改构建它。

描述#

libuniverse库声明了两个类:IcecreamTruck

Icecream对象具有一种口味,并提供了一个访问器来返回该口味。

Truck实例存储了一个Icecream对象的向量,并具有添加新口味、打印可用口味、配送冰淇淋等各种方法。

从C++的角度来看,Icecream实例被视为对象类型(指针语义),因为该类声明了虚方法。

相比之下,Truck没有定义虚函数,并且被处理为值类型(复制语义)。

因为Truck是一个值类型,并且它存储了一个指向Icecream指针的向量,必须考虑五项规则(实现复制构造函数、赋值运算符、移动构造函数、移动赋值运算符和析构函数)。

由于Icecream对象是可复制的,因此该类型必须定义一个clone()方法,以避免类型剪贴问题。

这两种类型及其方法将通过生成CPython代码的方式公开给Python。代码由shiboken生成,放置在分别以每个C++类型命名的单独的.cpp文件中。然后编译并链接到共享库中。共享库是一个CPython扩展模块,由Python解释器加载。

由于C++语言与Python有不同的语义,shiboken需要帮助来了解如何生成绑定代码。这是通过指定一个特殊的XML文件,称为类型系统文件来完成的。

在类型系统文件中,您可以指定以下内容:

  • 哪些C++类应该有绑定(Icecream、Truck),以及具有何种语义(值/对象)

  • 所有权规则(谁删除C++对象,C++还是Python)

  • 代码注入(用于各种shiboken不了解的特殊情况)

  • 包名(Python导入时使用的包名)

在这个例子中,我们将Icecream声明为对象类型,将Truck声明为值类型。clone()addIcecreamFlavor(Icecream*)在跨越语言边界传递参数对象时需要有关参数对象所有者的更多信息(在这种情况下,C++将删除对象)。

Truck有字符串arrivalMessage的获取器和设置器。在类型系统文件中,我们将其声明为Python中的属性

<property type="std::string" name="arrivalMessage" get="getArrivalMessage" set="setArrivalMessage"/>

然后可以用更Python的方式使用它

special_truck.arrivalMessage = "A new SPECIAL icecream truck has arrived!\n"

shiboken生成C++代码后,CMake从代码生成扩展模块,这些类型可通过导入它们的原始C++名称直接在Python中访问。

from Universe import Icecream, Truck

C++包装对象的构建与Python相同

icecream = Icecream("vanilla")
truck = Truck()

C++构造函数映射到Python的__init__方法。

class VanillaChocolateIcecream(Icecream):
    def __init__(self, flavor=""):
        super().__init__(flavor)

可以使用C++名称通过常规Python方法访问C++方法

truck.addIcecreamFlavor(icecream)

继承与常规Python类的工作方式相同,虚拟C++方法可以通过定义与C++类中相同的名称的方法来重写。

class VanillaChocolateIcecream(Icecream):
    # ...
    def getFlavor(self):
        return "vanilla sprinked with chocolate"

main.py脚本演示了这些类型的用法。

CMake项目文件包含许多注释,解释了那些对构建过程感兴趣的人的构建规则。

构建项目

此示例只能使用CMake构建。以下要求必须满足:

  • 将PySide包安装到当前活动Python环境中(系统或virtualenv)

  • CMake的新版本(3.16+)。

  • ninja

对于Windows,您还需要

  • 一个活动在终端中的Visual Studio环境

  • 选择正确的visual studio架构(32位或64位)

  • 请确保您的Python解释器和绑定项目构建配置相同(全部为发布版,这更为常见,或者全部为调试版)。

构建使用pyside_config.py文件,使用当前PySide/Shiboken安装配置项目。

使用CMake#

您可以在终端中执行以下命令(根据您的文件系统布局稍作修改)来构建和运行此示例:

macOS/Linux

cd ~/pyside-setup/examples/samplebinding

在Windows上

cd C:\pyside-setup\examples\samplebinding
mkdir build
cd build
cmake -S.. -B. -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=cl.exe
ninja
ninja install
cd ..

使用Python模块#

然后最终示例可以通过以下方式运行:

python main.py

main.py脚本中,在从Universe模块导入类后,从Icecream派生两种类型,用于不同的“口味”。然后,创建一个truck来递送一些普通口味的冰淇淋和两个特别的。

如果配送失败,将创建一个新的truck,其中复制了旧口味,并添加了一种新的神奇口味,这将确保让所有客户都满意。

尝试运行它以查看冰淇淋是否已递送。

Windows故障排除#

可能的情况是CMake为不同的架构选择了错误的编译器,但它可以通过设置环境变量CC来显式解决

set CC=cl

在命令行上传递编译器

cmake -S.. -B. -DCMAKE_C_COMPILER=cl.exe -DCMAKE_CXX_COMPILER=cl.exe

或通过使用-G选项

cmake -S.. -B. -G "Visual Studio 14 Win64"

如果使用了-G "Visual Studio 14 Win64"选项,则将生成一个sln文件,可以使用MSBuild代替ninja使用。在这种情况下,既构建又安装的最简单方法是使用cmake可执行文件

cmake --build . --target install --config Release

请注意,使用"Ninja"生成器比使用MSBuild生成器更为推荐,因为MSBuild生成器为调试和发布版都生成配置,这可能会导致在至少一次意外构建错误配置的情况下产生构建错误。

Virtualenv支持#

如果从启用了Python虚拟环境的终端启动python应用程序,则将使用该环境的包进行python模块导入过程。在这种情况下,请确保在虚拟环境活动时构建绑定,以便构建系统可以获取正确的python共享库和PySide6 / shiboken包。

Linux共享库注意事项#

对于此示例的目的,我们链接到依赖的共享库libshiboken的绝对路径,因为库的安装是通过wheel完成的,并且没有干净的解决方案在wheel包中包含符号链接(因此,将-lshiboken传递给连接器将无法工作)。

Windows注意事项#

绑定的构建配置(调试或发布)应与PySide的构建配置相匹配;否则,应用程序将无法正常工作。

实际上,这意味着唯一支持的项目配置是

  1. 释放配置的绑定构建加 PySide 的 setup.py 不带 --debug 标志 + 用于 PySide 构建过程的 python.exe + 用于引入的共享库的 python39.dll

  2. 调试配置构建的应用程序 + PySide 的 setup.py 带有 --debug 标志 + 用于 PySide 构建过程的 python_d.exe + 用于引入的共享库的 python39_d.dll

这是必要的,因为所有需要关联的共享库都必须链接到同一个 C++ 运行库(msvcrt.dllmsvcrtd.dll)。为了尽可能自包含,使用中的共享库(pyside6.dllshiboken6.dll)被硬链接到应用程序的构建文件夹中。

下载此示例

Shiboken 生成器需要一个包含我们所感兴趣的数据类型的头文件

// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#ifndef BINDINGS_H
#define BINDINGS_H

#include "icecream.h"
#include "truck.h"

#endif // BINDINGS_H

Shiboken 需要一个基于 XML 的类型系统文件,定义 C++ 和 Python 类型之间的关系。

它声明了上述两个类。其中一个作为“对象类型”,另一个作为“值类型”。主要的区别在于对象类型在生成的代码中以指针的形式传递,而值类型则是复制的(值语义)。

通过在类型系统文件中指定这些类的名称,Shiboken 将自动尝试为这些类的所有方法生成绑定。除非您想修改它们,否则不需要在 XML 文件中手动提及所有方法。

对象拥有权规则

Shiboken 不知道 Python 或 C++ 谁负责释放 Python 代码中分配的 C++ 对象,这样的假设可能会导致错误。可能存在 Python 应当在 Python 对象的引用计数变为零时释放 C++ 内存的情况,但它绝不能仅仅假设它不会被底层的 C++ 库删除,或者它可能属于另一个对象(如 QWidgets)。

在我们的情况下,clone() 方法仅在 C++ 库内部调用,并且我们假设 C++ 代码负责释放复制的对象。

至于 addIcecreamFlavor(),我们知道 Truck 拥有 Icecream 对象,并在 Truck 销毁时将其删除。这就是为什么在类型系统文件中将拥有权设置为“c++”的原因,这样当相应的 Python 名称超出作用域时,不会删除 C++ 对象。

<?xml version="1.0"?>
<!--
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
-->
<typesystem package="Universe">

    <object-type name="Icecream">
        <!-- By default the ownership of an object created in Python is tied
             to the Python name pointing to it. In order for the underlying
             C++ object not to get deleted when the Python name goes out of
             scope, we have to transfer ownership to C++.
             -->
        <modify-function signature="clone()">
            <modify-argument index="0">
                <define-ownership owner="c++"/>
            </modify-argument>
        </modify-function>
    </object-type>

    <value-type name="Truck">
        <!-- Same ownership caveat applies here. -->
        <property type="std::string" name="arrivalMessage" get="getArrivalMessage" set="setArrivalMessage"/>
        <modify-function signature="addIcecreamFlavor(Icecream*)">
            <modify-argument index="1">
                <define-ownership owner="c++"/>
            </modify-argument>
        </modify-function>
    </value-type>

</typesystem>
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "icecream.h"

#include <iostream>

Icecream::Icecream(const std::string &flavor) : m_flavor(flavor) {}

Icecream::~Icecream() = default;

std::string Icecream::getFlavor() const
{
    return m_flavor;
}

Icecream *Icecream::clone()
{
    return new Icecream(*this);
}

std::ostream &operator<<(std::ostream &str, const Icecream &i)
{
    str << i.getFlavor();
    return str;
}
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#ifndef ICECREAM_H
#define ICECREAM_H

#include "macros.h"

#include <iosfwd>
#include <string>

class BINDINGS_API Icecream
{
public:
    explicit Icecream(const std::string &flavor);
    virtual Icecream *clone();
    virtual ~Icecream();
    virtual std::string getFlavor() const;

private:
    std::string m_flavor;
};

std::ostream &operator<<(std::ostream &str, const Icecream &i);

#endif // ICECREAM_H
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#ifndef MACROS_H
#define MACROS_H

#if defined _WIN32 || defined __CYGWIN__
    // Export symbols when creating .dll and .lib, and import them when using .lib.
    #if BINDINGS_BUILD
        #define BINDINGS_API __declspec(dllexport)
    #else
        #define BINDINGS_API __declspec(dllimport)
    #endif
    // Disable warnings about exporting STL types being a bad idea. Don't use this in production
    // code.
    #pragma warning( disable : 4251 )
#else
    #define BINDINGS_API
#endif

#endif // MACROS_H
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

"""An example showcasing how to use bindings for a custom non-Qt C++ library"""

from Universe import Icecream, Truck


class VanillaChocolateIcecream(Icecream):
    def __init__(self, flavor=""):
        super().__init__(flavor)

    def clone(self):
        return VanillaChocolateIcecream(self.getFlavor())

    def getFlavor(self):
        return "vanilla sprinked with chocolate"


class VanillaChocolateCherryIcecream(VanillaChocolateIcecream):
    def __init__(self, flavor=""):
        super().__init__(flavor)

    def clone(self):
        return VanillaChocolateCherryIcecream(self.getFlavor())

    def getFlavor(self):
        base_flavor = super(VanillaChocolateCherryIcecream, self).getFlavor()
        return f"{base_flavor} and a cherry"


if __name__ == '__main__':
    leave_on_destruction = True
    truck = Truck(leave_on_destruction)

    flavors = ["vanilla", "chocolate", "strawberry"]
    for f in flavors:
        icecream = Icecream(f)
        truck.addIcecreamFlavor(icecream)

    truck.addIcecreamFlavor(VanillaChocolateIcecream())
    truck.addIcecreamFlavor(VanillaChocolateCherryIcecream())

    truck.arrive()
    truck.printAvailableFlavors()
    result = truck.deliver()

    if result:
        print("All the kids got some icecream!")
    else:
        print("Aww, someone didn't get the flavor they wanted...")

    if not result:
        special_truck = Truck(truck)
        del truck

        print("")
        special_truck.arrivalMessage = "A new SPECIAL icecream truck has arrived!\n"
        special_truck.arrive()
        special_truck.addIcecreamFlavor(Icecream("SPECIAL *magical* icecream"))
        special_truck.printAvailableFlavors()
        special_truck.deliver()
        print("Now everyone got the flavor they wanted!")
        special_truck.leave()
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include <iostream>
#include <random>

#include "truck.h"

Truck::Truck(bool leaveOnDestruction) : m_leaveOnDestruction(leaveOnDestruction) {}

Truck::Truck(const Truck &other)
{
    assign(other);
}

Truck &Truck::operator=(const Truck &other)
{
    if (this != &other) {
        m_flavors.clear();
        assign(other);
    }
    return *this;
}

Truck::Truck(Truck &&other) = default;

Truck& Truck::operator=(Truck &&other) = default;

Truck::~Truck()
{
    if (m_leaveOnDestruction)
        leave();
}

void Truck::addIcecreamFlavor(Icecream *icecream)
{
    m_flavors.push_back(IcecreamPtr(icecream));
}

void Truck::printAvailableFlavors() const
{
    std::cout << "It sells the following flavors: \n";
    for (const auto &flavor : m_flavors)
        std::cout << "  * "  << *flavor << '\n';
    std::cout << '\n';
}

void Truck::arrive() const
{
    std::cout << m_arrivalMessage;
}

void Truck::leave() const
{
    std::cout << "The truck left the neighborhood.\n";
}

void Truck::setLeaveOnDestruction(bool value)
{
    m_leaveOnDestruction = value;
}

void Truck::setArrivalMessage(const std::string &message)
{
    m_arrivalMessage = message;
}

std::string Truck::getArrivalMessage() const
{
    return m_arrivalMessage;
}

void Truck::assign(const Truck &other)
{
    m_flavors.reserve(other.m_flavors.size());
    for (const auto &f : other.m_flavors)
        m_flavors.push_back(IcecreamPtr(f->clone()));
}

bool Truck::deliver() const
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(1, 2);

    std::cout << "The truck started delivering icecream to all the kids in the neighborhood.\n";
    bool result = false;

    if (dist(mt) == 2)
        result = true;

    return result;
}
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#ifndef TRUCK_H
#define TRUCK_H

#include "icecream.h"
#include "macros.h"

#include <memory>
#include <vector>

class BINDINGS_API Truck
{
public:
    explicit Truck(bool leaveOnDestruction = false);
    Truck(const Truck &other);
    Truck& operator=(const Truck &other);
    Truck(Truck &&other);
    Truck& operator=(Truck &&other);

    ~Truck();

    void addIcecreamFlavor(Icecream *icecream);
    void printAvailableFlavors() const;

    bool deliver() const;
    void arrive() const;
    void leave() const;

    void setLeaveOnDestruction(bool value);

    void setArrivalMessage(const std::string &message);
    std::string getArrivalMessage() const;

private:
    using IcecreamPtr = std::shared_ptr<Icecream>;

    void assign(const Truck &other);

    bool m_leaveOnDestruction = false;
    std::string m_arrivalMessage = "A new icecream truck has arrived!\n";
    std::vector<IcecreamPtr> m_flavors;
};

#endif // TRUCK_H
# Copyright (C) 2023 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause

cmake_minimum_required(VERSION 3.18)
cmake_policy(VERSION 3.18)

# Enable policy to not use RPATH settings for install_name on macOS.
if(POLICY CMP0068)
  cmake_policy(SET CMP0068 NEW)
endif()

# Consider changing the project name to something relevant for you.
project(SampleBinding)

# ================================ General configuration ======================================

# Set CPP standard to C++17 minimum.
set(CMAKE_CXX_STANDARD 17)

# The sample library for which we will create bindings. You can change the name to something
# relevant for your project.
set(sample_library "libuniverse")

# The name of the generated bindings module (as imported in Python). You can change the name
# to something relevant for your project.
set(bindings_library "Universe")

# The header file with all the types and functions for which bindings will be generated.
# Usually it simply includes other headers of the library you are creating bindings for.
set(wrapped_header ${CMAKE_SOURCE_DIR}/bindings.h)

# The typesystem xml file which defines the relationships between the C++ types / functions
# and the corresponding Python equivalents.
set(typesystem_file ${CMAKE_SOURCE_DIR}/bindings.xml)

# Specify which C++ files will be generated by shiboken. This includes the module wrapper
# and a '.cpp' file per C++ type. These are needed for generating the module shared
# library.
set(generated_sources
    ${CMAKE_CURRENT_BINARY_DIR}/${bindings_library}/universe_module_wrapper.cpp
    ${CMAKE_CURRENT_BINARY_DIR}/${bindings_library}/icecream_wrapper.cpp
    ${CMAKE_CURRENT_BINARY_DIR}/${bindings_library}/truck_wrapper.cpp)


# ================================== Shiboken detection ======================================
# Use provided python interpreter if given.
if(NOT python_interpreter)
    if(WIN32 AND "${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
        find_program(python_interpreter "python_d")
        if(NOT python_interpreter)
            message(FATAL_ERROR
                "A debug Python interpreter could not be found, which is a requirement when "
                "building this example in a debug configuration. Make sure python_d.exe is in "
                "PATH.")
        endif()
    else()
        find_program(python_interpreter "python")
        if(NOT python_interpreter)
            message(FATAL_ERROR
                "No Python interpreter could be found. Make sure python is in PATH.")
        endif()
    endif()
endif()
message(STATUS "Using python interpreter: ${python_interpreter}")

# Macro to get various pyside / python include / link flags and paths.
# Uses the not entirely supported utils/pyside_config.py file.
macro(pyside_config option output_var)
    if(${ARGC} GREATER 2)
        set(is_list ${ARGV2})
    else()
        set(is_list "")
    endif()

    execute_process(
      COMMAND ${python_interpreter} "${CMAKE_SOURCE_DIR}/../utils/pyside_config.py"
              ${option}
      OUTPUT_VARIABLE ${output_var}
      OUTPUT_STRIP_TRAILING_WHITESPACE)

    if ("${${output_var}}" STREQUAL "")
        message(FATAL_ERROR "Error: Calling pyside_config.py ${option} returned no output.")
    endif()
    if(is_list)
        string (REPLACE " " ";" ${output_var} "${${output_var}}")
    endif()
endmacro()

# Query for the shiboken generator path, Python path, include paths and linker flags.
pyside_config(--shiboken-module-path shiboken_module_path)
pyside_config(--shiboken-generator-path shiboken_generator_path)
pyside_config(--python-include-path python_include_dir)
pyside_config(--shiboken-generator-include-path shiboken_include_dir 1)
pyside_config(--shiboken-module-shared-libraries-cmake shiboken_shared_libraries 0)
pyside_config(--python-link-flags-cmake python_linking_data 0)

set(shiboken_path "${shiboken_generator_path}/shiboken6${CMAKE_EXECUTABLE_SUFFIX}")
if(NOT EXISTS ${shiboken_path})
    message(FATAL_ERROR "Shiboken executable not found at path: ${shiboken_path}")
endif()


# ==================================== RPATH configuration ====================================


# =============================================================================================
# !!! (The section below is deployment related, so in a real world application you will want to
# take care of this properly with some custom script or tool).
# =============================================================================================
# Enable rpaths so that the built shared libraries find their dependencies.
set(CMAKE_SKIP_BUILD_RPATH FALSE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH ${shiboken_module_path} ${CMAKE_CURRENT_SOURCE_DIR})
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
# =============================================================================================
# !!! End of dubious section.
# =============================================================================================


# =============================== CMake target - sample_library ===============================


# Define the sample shared library for which we will create bindings.
set(${sample_library}_sources icecream.cpp truck.cpp)
add_library(${sample_library} SHARED ${${sample_library}_sources})
set_property(TARGET ${sample_library} PROPERTY PREFIX "")

# Needed mostly on Windows to export symbols, and create a .lib file, otherwise the binding
# library can't link to the sample library.
target_compile_definitions(${sample_library} PRIVATE BINDINGS_BUILD)


# ====================== Shiboken target for generating binding C++ files  ====================


# Set up the options to pass to shiboken.
set(shiboken_options --generator-set=shiboken --enable-parent-ctor-heuristic
    --enable-return-value-heuristic --use-isnull-as-nb-bool
    --avoid-protected-hack
    -I${CMAKE_SOURCE_DIR}
    -T${CMAKE_SOURCE_DIR}
    --output-directory=${CMAKE_CURRENT_BINARY_DIR}
    )

set(generated_sources_dependencies ${wrapped_header} ${typesystem_file})

# Add custom target to run shiboken to generate the binding cpp files.
add_custom_command(OUTPUT ${generated_sources}
                    COMMAND ${shiboken_path}
                    ${shiboken_options} ${wrapped_header} ${typesystem_file}
                    DEPENDS ${generated_sources_dependencies}
                    IMPLICIT_DEPENDS CXX ${wrapped_header}
                    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
                    COMMENT "Running generator for ${typesystem_file}.")


# =============================== CMake target - bindings_library =============================


# Set the cpp files which will be used for the bindings library.
set(${bindings_library}_sources ${generated_sources})

# Define and build the bindings library.
add_library(${bindings_library} MODULE ${${bindings_library}_sources})

# Apply relevant include and link flags.
target_include_directories(${bindings_library} PRIVATE ${python_include_dir})
target_include_directories(${bindings_library} PRIVATE ${shiboken_include_dir})
target_include_directories(${bindings_library} PRIVATE ${CMAKE_SOURCE_DIR})

target_link_libraries(${bindings_library} PRIVATE ${shiboken_shared_libraries})
target_link_libraries(${bindings_library} PRIVATE ${sample_library})

# Adjust the name of generated module.
set_property(TARGET ${bindings_library} PROPERTY PREFIX "")
set_property(TARGET ${bindings_library} PROPERTY OUTPUT_NAME
             "${bindings_library}${PYTHON_EXTENSION_SUFFIX}")
if(WIN32)
    if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
        set_property(TARGET ${bindings_library} PROPERTY SUFFIX "_d.pyd")
    else()
        set_property(TARGET ${bindings_library} PROPERTY SUFFIX ".pyd")
    endif()
endif()

# Make sure the linker doesn't complain about not finding Python symbols on macOS.
if(APPLE)
  set_target_properties(${bindings_library} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup")
endif(APPLE)

# Find and link to the python import library only on Windows.
# On Linux and macOS, the undefined symbols will get resolved by the dynamic linker
# (the symbols will be picked up in the Python executable).
if (WIN32)
    list(GET python_linking_data 0 python_libdir)
    list(GET python_linking_data 1 python_lib)
    find_library(python_link_flags ${python_lib} PATHS ${python_libdir} HINTS ${python_libdir})
    target_link_libraries(${bindings_library} PRIVATE ${python_link_flags})
endif()


# ================================= Dubious deployment section ================================

set(windows_shiboken_shared_libraries)

if(WIN32)
    # =========================================================================================
    # !!! (The section below is deployment related, so in a real world application you will
    # want to take care of this properly (this is simply to eliminate errors that users usually
    # encounter.
    # =========================================================================================
    # Circumvent some "#pragma comment(lib)"s in "include/pyconfig.h" which might force to link
    # against a wrong python shared library.

    set(python_versions_list 3 36 37 38 39)
    set(python_additional_link_flags "")
    foreach(ver ${python_versions_list})
        set(python_additional_link_flags
            "${python_additional_link_flags} /NODEFAULTLIB:\"python${ver}_d.lib\"")
        set(python_additional_link_flags
            "${python_additional_link_flags} /NODEFAULTLIB:\"python${ver}.lib\"")
    endforeach()

    set_target_properties(${bindings_library}
                           PROPERTIES LINK_FLAGS "${python_additional_link_flags}")

    # Compile a list of shiboken shared libraries to be installed, so that
    # the user doesn't have to set the PATH manually to point to the PySide6 package.
    foreach(library_path ${shiboken_shared_libraries})
        string(REGEX REPLACE ".lib$" ".dll" library_path ${library_path})
        file(TO_CMAKE_PATH ${library_path} library_path)
        list(APPEND windows_shiboken_shared_libraries "${library_path}")
    endforeach()
    # =========================================================================================
    # !!! End of dubious section.
    # =========================================================================================
endif()

# =============================================================================================
# !!! (The section below is deployment related, so in a real world application you will want to
# take care of this properly with some custom script or tool).
# =============================================================================================
# Install the library and the bindings module into the source folder near the main.py file, so
# that the Python interpeter successfully imports the used module.
install(TARGETS ${bindings_library} ${sample_library}
        LIBRARY DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}
        RUNTIME DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}
        )
install(FILES ${windows_shiboken_shared_libraries} DESTINATION ${CMAKE_CURRENT_SOURCE_DIR})
# =============================================================================================
# !!! End of dubious section.
# =============================================================================================