How to create a Cylinder TopoDS_Solid in OpenCASCADE

Also see How to create a Box TopoDS_Solid in OpenCASCADE and How to create a Cube TopoDS_Solid in OpenCASCADE

Using my OCCUtils library, you can easily create a cylinder of user-defined diameter and length:

#include <occutils/Primitive.hxx>

using namespace OCCUtils;

TopoDS_Solid myCube = Primitive::MakeCylinder(5.0 /* mm diameter */, 25.0 /* mm length */);

You can also define the orientation of the cylinder using Primites::Orientation::X, Primites::Orientation::Y or Primites::Orientation::Z:

#include <occutils/Primitive.hxx>
#include <vector>

using namespace OCCUtils;

TopoDS_Solid myCube = Primitive::MakeCylinder(5.0 /* mm diameter */,
    25.0 /* mm length */, Primitive::Orientation::X);

You can also center this cylinder on the length axis. The origin point (default: (0,0,0)) always lies on the cylinder’s main axis (i.e. along its length.

#include <occutils/Primitive.hxx>
#include <vector>

using namespace OCCUtils;

/*
 * Make a cube that is centered on the X- and Y axes
 */
TopoDS_Solid myCube = Primitive::MakeCylinder(5.0 /* mm diameter */, 25.0 /* mm length */,
    Primitive::Orientation::X,
    Primitive::CenterL);

Also you can use a specific point of origin as the third argument (gp_Pnt).

If you want to do it manually without OCCUtils, have a look at the OCC class BRepPrimAPI_MakeBox which you can use like this:

gp_Ax2 ax = /* Define origin point and direction of the cylinder here */;
BRepPrimAPI_MakeCylinder cyl(ax, diameter / 2.0, length);
cyl.Build();
TopoDS_Solid mySolid = cyl.Solid();

In this case, you have to center the object manually by computing the correct point of origin. In OCCUtils this is done using

// Compute offsets based on centering
if(center & CenterX) {
    origin.SetX(origin.X() - xSize / 2.0);
}
if(center & CenterY) {
    origin.SetY(origin.Y() - ySize / 2.0);
}
if(center & CenterZ) {
    origin.SetZ(origin.Z() - zSize / 2.0);
}