1

I'm trying to run a code written in C++ which should be the same as one I have in Python. They both use Fenics.

My problem is that I cannot translate a Python class into a C++ class.

For instance, my Python code is:

V = VectorFunctionSpace(mesh, "Lagrange", 1)
u = Function(V)
En = 5*dx - dot(3, u)*ds(2)

def f(self, x):
    u.vector()[:] = x
    return assemble(En)

The problem here is that the compiler cannot find En as it is not defined inside the class.

My C++ code:

double f(const GenericVector& x)
{
     u.vector() = x;
     return assemble(F);
}

int main()
{
   //...things that apparently work...
   Function u(Vh);
   MyClass::BilinearForm F;

}

How can I solve this?

8
  • How is it able to find u? Commented Aug 18, 2015 at 21:25
  • 2
    Neither u nor En are defined in the Python fragment either. Please give a minimal complete verifiable example. Commented Aug 18, 2015 at 21:34
  • It isn't. It's another compiler error. En and u are defined in the main and I cannot pass them to the class because f is a virtual method with a fixed signature. Commented Aug 18, 2015 at 21:37
  • Declare them outside a function (outside main) and use them as ::En and ::u. Commented Aug 18, 2015 at 21:41
  • @RolandSmith, I edited the question. Hope it's clearer now Commented Aug 18, 2015 at 21:43

2 Answers 2

4

C++ has globals in the same way Python has globals.

If you want access to something defined outside your class, either prefix it with its class name and make it static (MyClass::Thingy), make it a global, give it an accessor function (MyInstance.GetThingy()), or pass it in directly as an argument to functions that use it.

Sign up to request clarification or add additional context in comments.

Comments

0

As one of many methods, you can simply try defining F as global variable as follows:

...

MyClass::BilinearForm F; // The global scope

double f(const GenericVector& x)
{
     u.vector() = x;
     return assemble(F);
}

int main()
{
   //...things that apparently work...
   Function u(Vh);
   // you can use F here or call the function f
    ...

}

Here F is a global variable and you can use it in any method in this scope. I do not know how your class is defined or whether you are using a custom namespace but you may get rid of the scope resolution (MyClass::) part based on your implementation if BilinearForm is an accessible class here. You can also define F as a static variable so if you could provide more details, I am sure you might get more precise feedback.

Hope that helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.