FEM中从c++函数到python函数

Chinese forum
Post Reply
User avatar
johnwang
Posts: 578
Joined: Sun Jan 27, 2019 12:41 am

FEM中从c++函数到python函数

Post by johnwang » Tue Oct 27, 2020 4:21 am

src/Mod/Fem目录下App和Gui子目录是c++函数,其他的子目录为python函数。如果用python编程,如何调用c++函数呢?

我们看下src/Mod/Fem/Gui/ViewProviderFemMesh.cpp, 其中有个applyDisplacementToNodes函数:

Code: Select all

void ViewProviderFemMesh::applyDisplacementToNodes(double factor)
{
    if(DisplacementVector.size() == 0)
        return;

    float x,y,z;
    // set the point coordinates
    long sz = pcCoords->point.getNum();
    SbVec3f* verts = pcCoords->point.startEditing();
    for (long i=0;i < sz ;i++) {
        verts[i].getValue(x,y,z);
        // undo old factor#
        Base::Vector3d oldDisp = DisplacementVector[i] * DisplacementFactor;
        x -= oldDisp.x;
        y -= oldDisp.y;
        z -= oldDisp.z;
        // apply new factor
        Base::Vector3d newDisp = DisplacementVector[i] * factor;
        x += newDisp.x;
        y += newDisp.y;
        z += newDisp.z;
        // set the new value
        verts[i].setValue(x,y,z);
    }Gui/
    pcCoords->point.finishEditing();

    DisplacementFactor = factor;
}
把它开放给python, 需要包装一下。包装函数在src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp里:

Code: Select all

PyObject* ViewProviderFemMeshPy::applyDisplacement(PyObject * args)
{
    double factor;
    if (!PyArg_ParseTuple(args, "d", &factor))
        return 0;

    this->getViewProviderFemMeshPtr()->applyDisplacementToNodes(factor);

    Py_Return;
}
这样c++的applyDisplacementToNodes函数变成了python的applyDisplacement函数。

python中对这个函数的调用可以看femguiobjects\_ViewProviderFemResultMechanical.py:

Code: Select all

    def update_displacement(self, factor=None):
        if factor is None:
            if FreeCAD.FEM_dialog["show_disp"]:
                factor = self.result_widget.sb_displacement_factor.value()
            else:
                factor = 0.0
        self.mesh_obj.ViewObject.applyDisplacement(factor)
这样你就可以用c++写一些功能,然后在python里调用了。
hfc series CAE workbenches for FreeCAD (hfcNastran95, hfcMystran, hfcFrame3DD, hfcSU2 and more)

Post Reply