NREL / EnergyPlus

EnergyPlus™ is a whole building energy simulation program that engineers, architects, and researchers use to model both energy consumption and water use in buildings.
https://energyplus.net
Other
1.1k stars 384 forks source link

Using the EnergyPlusAPI with C# #10146

Closed tkdogan closed 1 year ago

tkdogan commented 1 year ago

Is there any documentation on how to use the EnergyPlus API with .NET C#? This article states that there should be an "EnergyPlusWrapper.dll" but I am having trouble finding that.

Myoldmopar commented 1 year ago

That article was made by a user and is littered with mistakes. It also mentions we package a .jar file for EnergyPlus, which we do not. The example code is also woefully wrong. It's not to say that some of the ideas in the article are bad, but it appears to have been almost entirely generated artificially. I've reached out to them to ask them about it; it is already causing confusion as users see it on LinkedIn.

tkdogan commented 1 year ago

Thanks for the quick clarification. So no support for C# at this point?

Myoldmopar commented 1 year ago

Not directly, although in years past I've called unmanaged libraries from .Net (VB.Net at the time), and it was fine. It's possible you could just add a dependency on our raw C API and make use of EnergyPlus as a library.

tkdogan commented 1 year ago

When I try what you suggest, I get an error. Could you share some more pointers on how you did this? image

Myoldmopar commented 1 year ago

(Finds code in his archive from 2007)

I had to load up the unmanaged DLL using raw Windows DLL function calls, such as:

<DllImport("kernel32.dll")> Public Shared Function LoadLibrary(ByVal moduleName as String) As IntPtr

Once the DLL was found, I would similarly use GetProcAddress to find the callable functions inside the DLL. I could then register one of my VB.Net functions as a callback using Marshal.GetDelegateForFunctionPointer(AddressFromGetProcAddress, GetType(CallbackType))

Then by executing EnergyPlus' main function as a DLL, I could do operations in the callback. Don't forget to FreeDLL!

Now, this was calling a Fortran DLL from VB.Net, in 2007. Things have gotten better since then. I would imagine you can find info about calling C from C# from a quick web search. Here's what ChatGPT says lol:

// mydll.h
#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif
MYDLL_API int Add(int a, int b);

// mydll.c
#include "mydll.h"
int Add(int a, int b) {
    return a + b;
}

// C#
using System;
using System.Runtime.InteropServices;

class Program {
    [DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int Add(int a, int b);

    static void Main() {
        int result = Add(5, 7);
        Console.WriteLine("Result: " + result);
    }
}