bodong1987 / UnrealSharp

A free plugin that allows you to develop with .net 8.0 and C# 12 in UnrealEngine5
MIT License
59 stars 4 forks source link

C# Invocation From Unreal #1

Closed stonstad closed 7 months ago

stonstad commented 8 months ago

Your project is very compelling! Thank you for making this happen.

Is there a code example which demonstrates what invoking code from Unreal to C# look like?

For example, let's say I have a C# class named Foo, and I want to instantiate it, hold a reference to it, and invoke methods and properties from within Unreal.

If this is possible and what does the code look like?

bodong1987 commented 7 months ago

Your project is very compelling! Thank you for making this happen.

Is there a code example which demonstrates what invoking code from Unreal to C# look like?

For example, let's say I have a C# class named Foo, and I want to instantiate it, hold a reference to it, and invoke methods and properties from within Unreal.

If this is possible and what does the code look like?

Of course you can, and it's very simple, some example codes: https://github.com/bodong1987/UnrealSharp/blob/main/Plugins/UnrealSharp/Source/UnrealSharp/Public/ICSharpLibraryAccessor.h
https://github.com/bodong1987/UnrealSharp/blob/main/Plugins/UnrealSharp/Source/UnrealSharp/Private/CSharpLibraryAccessor.h https://github.com/bodong1987/UnrealSharp/blob/main/Plugins/UnrealSharp/Source/UnrealSharp/Private/CSharpLibraryAccessor.cpp

It's just that if you directly access the C# code, you need to handle operations such as boxing and unboxing of the return value yourself, which is not very convenient. And this is almost like the bottom layer is dependent on the upper layer, which is not a good design idea. Of course, in some specific environments and needs, it is not impossible.

If you want to create an instance of a C# object directly in C++ and save it, you need to create a GCHandle to ensure that the C# object will not be collected by the C# garbage collector. This is how UnrealSharp does it internally: https://github.com/bodong1987/UnrealSharp/blob/main/Plugins/UnrealSharp/Source/UnrealSharp/Public/ICSharpRuntime.h https://github.com/bodong1987/UnrealSharp/blob/main/Plugins/UnrealSharp/Source/UnrealSharp/Private/CSharpObjectHandle.h https://github.com/bodong1987/UnrealSharp/blob/main/Plugins/UnrealSharp/Source/UnrealSharp/Private/CSharpObjectHandle.cpp

create C# object need two steps:1. create an empty object 2. invoke constructor on it. https://github.com/bodong1987/UnrealSharp/blob/main/Plugins/UnrealSharp/Source/UnrealSharp/Private/CSharpObjectTable.cpp#L47

You can also look at this method:
https://stackoverflow.com/a/39803574/916216