cs-script icon indicating copy to clipboard operation
cs-script copied to clipboard

DllImport how to use in script

Open ghost opened this issue 1 year ago • 5 comments

How can i use DllImport attribute like below? When try to use it the compiler trows an type loading error

[DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

Error: InvalidCastException unable to cast object of type 'Mono.CSharp.ImportedTypeDefinition' to type 'Mono.CSharp.MemberCore'

ghost avatar Jan 23 '24 17:01 ghost

I am not sure what version of the script engine you are using and what is the hosting platform. IE the current version of CS-Script has no dependency on Mono.

Anyway, the simple answer is "Exactly as with any C# code". image

oleg-shilo avatar Jan 24 '24 05:01 oleg-shilo

So I was on an older version of CS Script, after version 3.29.0 the script runs, but when using CS-Script.bin to load the code it now is throwing the following error:

FileNotFoundException: The file or assembly 'Microsoft.CodeAnalysis.Scripting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies could not be loaded. The system was unable to locate the specified file.

ghost avatar Jan 24 '24 11:01 ghost

I've changed the EvaluatorEngine to be CodeDom and it now works without problem, can't be sure why... My Project compiles a DLL that then is inject to a third party program, maybe this affects what AppDomain is used to add the references?

ghost avatar Jan 24 '24 12:01 ghost

If some one has the same problem and want to use newer c# syntax this is how i solve it

CSScript.EvaluatorConfig.Engine = EvaluatorEngine.CodeDom;
                    CSScript.GlobalSettings.UseAlternativeCompiler = "PATH TO DLL\CSSRoslynProvider.dll";
                    CSScript.GlobalSettings.RoslynDir = "PATH TO Package\Microsoft.Net.Compilers.2.2.0\tools";

execute the following to get the DLL and the Microsoft Net Compilers -> Install-Package CS-Script.RoslynProvider

ghost avatar Jan 24 '24 13:01 ghost

And if you prefer to use Roslyn then you need to add Microsoft.CodeAnalysis.Scripting packages. The current CS-Script does it automatically but the old one needed the user to do it manually.

oleg-shilo avatar Jan 25 '24 05:01 oleg-shilo