Jump to content

Welcome to eMastercam

Register now to participate in the forums, access the download area, buy Mastercam training materials, post processors and more. This message will be removed once you have signed in.

Use your display name or email address to sign in:

c# dynamic keyword equvalent in c++/cli


Recommended Posts

Hi,

I am using Iron python to implementing a python scripting interface, my python script can access my c++/cli dll functions no problem, but the nethook that runs the script seems to only work using the dynamic keyword in c#, I was hoping there was some way to reproduce the same result in c++/cli?

example

:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace PythonScript
{
    public class LinkScript : Mastercam.App.NetHook3App
    {
        /// <summary> This method serves as the main entry point for the NetHook. </summary>
        ///
        /// <param name="param"> The parameter (optional). </param>
        ///
        /// <returns> A MCamReturn return type code. </returns>
        public override Mastercam.App.Types.MCamReturn Run(int param)
        {
           var ipy = Python.CreateRuntime();
           dynamic PythonSource = ipy.UseFile("PythonSource.py");
           PythonSource.RunScript();//this only works in c#
            return Mastercam.App.Types.MCamReturn.NoErrors;
        }
        };
}

python code:

import sys
import clr
#add the reference to our .net sdk library
clr.AddReferenceToFileAndPath(r'C:\Users\Peter.Evans\Desktop\Visual Studio\NetSDK\x64\Release\NetSDK.dll')
#import the SearchTools Module
from NetSDK import SearchTools
#############################
#/////Class Definitions/////#
#############################

#############################
#////Function Definitions///#
#############################
#/// <summary> Retrieve the entities pointer within the database given the specified mask. </summary>
#///
#/// <param name="mask">		 The mask to restrict the search to. (0 = NO restriction) </param>
#///
#/// <returns> The pointer to the current database entity. </returns>
def GetFirstDatabasePointer():
   searchtools = SearchTools()
   requestedinfo = searchtools.GetFirstDatabasePointerExp()
   return requestedinfo
#/// <summary> Retrieve the next entitiy pointer within the database. </summary>
#///
#/// <param name="currentpointer">		 The current pointer to a mastercam entity. (0 = NO restriction) </param>
#///
#/// <returns> The next entity pointer within the database.</returns>
def GetNextDatabasePointer(currentpointer):
   searchtools = SearchTools()
   requestedinfo = searchtools.GetNextDatabasePointerExp(int(currentpointer))
   return requestedinfo

#///////////////////////////#

#///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#/// <summary> Retrieve the requested information from the database entity pointer given a parameter. </summary>
#///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#///
#/// <param name="entitypointer"> The pointer to the current database entity. </param>					///
#/// <param name="infotype"> The type of info to collect. </param>
#///
#//if (infotype == 0) info == eptr->id;
#//if (infotype == 1) inf0 == eptr->level;
#//if (infotype == 2) inf0 == eptr->color;
#//if (infotype == 3) inf0 == eptr->chook;
#//if (infotype == 4) inf0 == eptr->refs;
#//if (infotype == 5) inf0 == eptr->tp_refs;
#///			
#/// <returns> The requested information. </returns>
def GetDatabasePointerInfoExp(entitypointer,infotype):
   searchtools = SearchTools()
   requestedinfo = searchtools.GetDatabasePointerInfoExp(int(entitypointer),int(infotype))
   return requestedinfo

#/////////////////////////////////////////////////////////////////////////////////////
#/// <summary> Retrieve the requested information from the database entity pointer given a parameter. </summary>
#/////////////////////////////////////////////////////////////////////////////////////
#///
#/// <param name="entitypointer"> The pointer to the current database entity. </param>			///
#/// <param name="infotype"> The type of info to collect. </param>
#///
#//if (infotype == 0) info == ALIVE_BIT
#//if (infotype == 1) inf0 == BLANK_BIT
#//if (infotype == 2) inf0 == SELECT_BIT
#//if (infotype == 3) inf0 == TEMP_BIT
#//if (infotype == 4) inf0 == TEMP2_BIT
#//if (infotype == 5) inf0 == TEMP3_BIT
#///			
#/// <returns> True if succeeded. </returns>


def GetDatabasePointerBitsExp(entitypointer,infotype):
   searchtools = SearchTools()
   requestedinfo = searchtools.GetDatabasePointerBitsExp(int(entitypointer),int(infotype))
   return requestedinfo

#/////////////////////////////////////////////////////////////////////////////////////
#/// <summary> Retrieve the requested information from the database entity pointer given a parameter. </summary>
#/////////////////////////////////////////////////////////////////////////////////////
#///
#/// <param name="entitypointer"> The pointer to the current database entity. </param>			///
#/// <param name="infotype"> The type of info to collect. </param>
#/// <param name="selbitturnon"> If true, turn the sel bit on. </param>
#///
#//if (infotype == 0) info == ALIVE_BIT
#//if (infotype == 1) inf0 == BLANK_BIT
#//if (infotype == 2) inf0 == SELECT_BIT
#//if (infotype == 3) inf0 == TEMP_BIT
#//if (infotype == 4) inf0 == TEMP2_BIT
#//if (infotype == 5) inf0 == TEMP3_BIT
#///			
#/// <returns> True if succeeded. </returns>


def SetDatabasePointerBitsExp(entitypointer,infotype,selbitturnon):
   searchtools = SearchTools()
   searchtools.SetDatabasePointerBitsExp(int(entitypointer),int(infotype),int(selbitturnon))
#/// <summary> Retrieve the solidtag fromn thr supplied entity pointer within the database. </summary>
#///
#/// <param name="SolidPointer">	The supplied entity pointer within the database.</param>
#///
#/// <returns> The solidtag fromn the supplied entity pointer within the database.</returns>
def GetSolidTagFromSolidExp(SolidPointer):
       searchtools = SearchTools() 
       return searchtools.GetSolidTagFromSolidExp(int(SolidPointer))
#/// <summary> Retrieve  maxz in bottom view  fromn thr supplied entity pointer within the database. </summary>
#///
#/// <param name="SolidPointer">	the supplied entity pointer within the database. </param>
#///
#/// <returns> The maxz in bottom view fromn the supplied entity pointer within the database.</returns>
def GetMaxzDepthOnSolidExp(SolidPointer):
       searchtools = SearchTools()
       returnvalue = float(searchtools.GetMaxzDepthOnSolidExp(int(SolidPointer)))
       return returnvalue
#// <summary> Retrieve  minz in bottom view  fromn thr supplied entity pointer within the database. </summary>
#///
#/// <param name="SolidPointer">	the supplied entity pointer within the database. </param>
#///
#/// <returns> The minz in bottom view fromn the supplied entity pointer within the database.</returns>
def GetMinzDepthOnSolidExp(SolidPointer):
      searchtools = SearchTools()
      returnvalue = searchtools.GetMinzDepthOnSolidExp(int(SolidPointer))
      return returnvalue

#/// <summary>Creates a collection of surfaces from the supplied solid tag. </summary>
#///
#/// <param name="SolidPointer">	The supplied solid tag.. </param>
#///
#/// <returns> A collection of surfaces from the supplied solid tag.</returns>
#/// <returns> A collection of surfaces from the supplied solid tag.</returns>
def CreateSldEdgesFromTagExp(sldtag,color,level,upperlimit,lowerlimit):
    searchtools = SearchTools()
    searchtools.CreateSldFacesFromTagExp(int(sldtag),int(color),int(level),float(upperlimit), float(lowerlimit))
#/// <summary> Demonstrates creating a silhouette boundary. </summary>
#///
#/// <returns> The number of entities created for the new silhouette boundary. </returns>
def ColorInnerOuterSelectedChain(outercolor,innercolor):
   	searchtools = SearchTools()
        searchtools.ColorInnerOuterSelectedChain(int(outercolor),int(innercolor))
def CreateSilhouetteBoundaryExp(pointer,leveltoset):
     searchtools = SearchTools()
     retval = searchtools.CreateSilhouetteBoundaryExp(int(pointer),int(leveltoset))
     return retval
	
	
def MessageBoxDisplayNumber(info):
   searchtools = SearchTools()
   returnvalue = searchtools.MessageBoxDisplayNumber(int(info))
   return returnvalue

def MessageBoxDisplayFloat(info):
   searchtools = SearchTools()
   returnvalue = searchtools.MessageBoxDisplayFloat(float(info))
   return returnvalue
#// <summary> Retrieves  a list of entity pointers from within the database. </summary>
#///
#/// <param name="id">	the supplied entity id to search for within the database. </param>
#///
#/// <returns> The a list of entity pointers from within the database.</returns>
#P_ID = 1 //point
#L_ID = 2 //line
#A_ID = 4 //Arc
#S_ID = 8 //Parametric Spline
#N_ID = 16//Nurbs Spline
#SURF_ID = 256 //surface
#SOLID_ID = 65536 //solid
def CreatePointerList(idlist):
     alist = []
     pointer = GetFirstDatabasePointer()
     while(pointer != 0):
        if GetDatabasePointerBitsExp(pointer,0):
             for id in idlist:
               if GetDatabasePointerInfoExp(pointer,0) == int(id):
                  alist.append(pointer)
        nextpointer = GetNextDatabasePointer(pointer)
        pointer = nextpointer
     return alist

#//if (infotype == 0) info == ALIVE_BIT
#//if (infotype == 1) inf0 == BLANK_BIT
#//if (infotype == 2) inf0 == SELECT_BIT
#//if (infotype == 3) inf0 == TEMP_BIT
#//if (infotype == 4) inf0 == TEMP2_BIT
#//if (infotype == 5) inf0 == TEMP3_BIT
def FilterEntListByBitOn(bit,list):
    filteredlist = []
    for pointer in list:
        if GetDatabasePointerBitsExp(pointer,int(bit)):
           filteredlist.append(pointer)
    return filteredlist
#//if (bit == 0) info == ALIVE_BIT
#//if (bit == 1) inf0 == BLANK_BIT
#//if (bit == 2) inf0 == SELECT_BIT
#//if (bit == 3) inf0 == TEMP_BIT
#//if (bit == 4) inf0 == TEMP2_BIT
#//if (bit == 5) inf0 == TEMP3_BIT
def SetEntListBit(bit,list,bitstate):
    for pointer in list:
        SetDatabasePointerBitsExp(int(pointer),int(bit),int(bitstate))

def CreateListOfAliveSolids():
     solidparams = [65536]
     alist = CreatePointerList(solidparams)
     return alist
def CreateListOfAliveWireframe():
     wframeparams = [2,4,8,16]
     wframelist = CreatePointerList(wframeparams)
     return wframelist

def GetPtrsFromNewSilhouetteBoundary(pointer,newlevel):
      CreateSilhouetteBoundaryExp(int(pointer),int(newlevel))
      wframeparams = [2,4,8,16]
      wframelist = CreatePointerList(wframeparams)
      return wframelist
def SelectAllEntsInList(list):
    for pointer in list:
         SetDatabasePointerBitsExp(int(pointer),2,1)
def UnSelectAllEntsInList(list):
    for pointer in list:
         SetDatabasePointerBitsExp(int(pointer),2,0)
def RunScript():
     solidlist = CreateListOfAliveSolids()
     for pointer in solidlist:
         #create a new silhouetteboundary and return a list of pointers #create new geomtery on level 50
         wframelist = GetPtrsFromNewSilhouetteBoundary(pointer,50)
         #filter the list of pointers to only include temp2(new) entities
         temp2wframelist = FilterEntListByBitOn(4,wframelist)
         #Select all entities in list
         SelectAllEntsInList(temp2wframelist)
         #change the color of the outermost chain
         ColorInnerOuterSelectedChain(50,55)
         #Set temp2 bit off
         SetEntListBit(4,temp2wframelist,0)    
         #get solid tag 
         solidtag = GetSolidTagFromSolidExp(pointer)
         #get solid max zvalue
         solidmaxz = GetMaxzDepthOnSolidExp(pointer)
         #get solid min zvalue
         solidminz = GetMinzDepthOnSolidExp(pointer)
         #create top solid entities
         CreateSldEdgesFromTagExp(solidtag,2,10, solidmaxz + .002,solidmaxz - .002)
         topwireframelist = CreateListOfAliveWireframe()
         temp2topwframelist = FilterEntListByBitOn(4,topwframelist)
         CreateSldEdgesFromTagExp(solidtag,2,20, solidminz + .002,solidminz - .002)

 

Link to comment
Share on other sites
//CallScript.cpp
//reference needed to Microsoft.Scripting & IronPython

void main()
{

	auto pythonengine = IronPython::Hosting::Python::CreateEngine();
	auto scope = pythonengine->CreateScope();
	pythonengine->ExecuteFile("script.py", scope);
	auto scriptrunner = scope->GetVariable("Scriptrunner");
	auto scriptrunnerInstance = pythonengine->Operations->CreateInstance(scriptrunner);
	auto result = pythonengine->Operations->InvokeMember(scriptrunnerInstance, "runscript");
	System::Console::WriteLine(result);//no dynamic cast
	auto stringresult = dynamic_cast<System::String^>(result);
	System::Console::WriteLine(stringresult);//dynamic cast
	System::Console::ReadKey();
}

#calling iron python from c++/cli project ^

script.py
class Scriptrunner:
    def runscript(self):
        return 'Python script function activated!'

#iron python code ^

 

Hi,

I found an easier option than what I was attempting to do before, I posted it above. ^

Link to comment
Share on other sites
On 2/17/2020 at 5:20 PM, Roger Martin from CNC Software said:

I didn't manage that method,it seems like what the compiler does with the dynamic keyword is beyond me at least for now,

however this helped me a lot https://stackoverflow.com/questions/21427081/need-an-easy-way-to-embedd-ironpython-with-c-cli

Link to comment
Share on other sites

This is important so I can easily package my scripting system into one dll, even if  the c++ stuff has to be loaded from a separate dll, it doesn't affect the deployment, 1 dll that will be able to loaded any scripts the user creates.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.

Join us!

eMastercam - your online source for all things Mastercam.

Together, we are the strongest Mastercam community on the web with over 56,000 members, and our online store offers a wide selection of training materials for all applications and skill levels.

Follow us

×
×
  • Create New...